package com.budwk.app.sqfw.services.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.common.config.AppException;
import com.budwk.app.common.rocketmq.RocketMQServer;
import com.budwk.app.dfxyWechatMP.DfxyWeChatMPUtils;
import com.budwk.app.exception.ServiceException;
import com.budwk.app.jim.SqfwWebSocket;
import com.budwk.app.jim.WebSocketMsgDTO;
import com.budwk.app.sms.dto.SmsMsgDTO;
import com.budwk.app.sms.service.OpaSmsService;
import com.budwk.app.sms.service.ZtSmsService;
import com.budwk.app.sqfw.bo.PdfResourceSortBO;
import com.budwk.app.sqfw.component.CommonComponent;
import com.budwk.app.sqfw.component.FromSummaryComponent;
import com.budwk.app.sqfw.component.MeetingMinutesComponent;
import com.budwk.app.sqfw.constants.BigPlaceInfoConstants;
import com.budwk.app.sqfw.constants.CommonConstants;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.dto.*;
import com.budwk.app.sqfw.enums.*;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.services.common.SqfwCustomForAdminCommonService;
import com.budwk.app.sqfw.vo.*;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfExcelGenerator;
import com.budwk.app.sqfwV2.service.CenturyCitySecurityService;
import com.budwk.app.sqfwV2.service.centuryCity.OldCareServiceStationExcelService;
import com.budwk.app.sqfwV2.service.dayingRoad.DaYingLuRedWhiteRecordExcelService;
import com.budwk.app.sqfwV2.service.dayingRoad.DaYingLuRedWhiteRecordPdfService;
import com.budwk.app.sqfwV2.service.meeting.MeetingService;
import com.budwk.app.sqfwV2.service.publicSecurity.PublicSecurityService;
import com.budwk.app.sqfwV2.service.weiqingmen.SafetyCheckExcelService;
import com.budwk.app.sqfwV2.service.weiqingmen.SafetyCheckPdfService;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysLogService;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.poiUtils.*;
import com.budwk.app.util.poiUtils.fireHiddenExcel.FireHiddenExcelFactory;
import com.budwk.app.util.poiUtils.fireHiddenExcel.impl.YuHongFireHiddenExcel;
import com.budwk.app.util.poiUtils.fireHiddenOffice.FireHiddenOfficeFactory;
import com.budwk.app.util.poiUtils.fireHiddenOffice.GeneratePdfConverge;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.budwk.starter.common.exception.BaseException;
import com.budwk.starter.common.result.Result;
import com.budwk.starter.common.result.ResultCode;
import com.budwk.starter.database.service.BaseServiceImpl;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.data.PictureRenderData;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.entity.annotation.Table;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SimpleCriteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.impl.PropertiesProxy;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.util.NutMap;
import org.nutz.trans.Trans;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.budwk.app.sqfw.enums.StreetEnum.DA_YING_LU_STREET;
import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.*;

/**
 * @author ZY.Wang
 * @since 2023/7/17
 */
@Slf4j
@IocBean(args = {"refer:dao"})
public class SqfwFormSummaryServiceImpl extends BaseServiceImpl<Sqfw_formSummary> implements SqfwFormSummaryService {
    public SqfwFormSummaryServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private SysUnitService sysUnitService;

    @Inject
    private SqfwCompleteflowService sqfwCompleteflowService;

    @Inject
    private SqfwWebSocket sqfwWebSocket;

    @Inject
    private SqfwServicerecordService sqfwServicerecordService;

    @Inject
    private OpaSmsService opaSmsService;

    @Inject
    private SysUserService sysUserService;

    @Inject
    private RocketMQServer rocketMQServer;

    @Inject
    private SqfwReportFileService reportFileService;

    @Inject
    private SqfwWorkorderService sqfwWorkorderService;

    @Inject
    private SqfwCenSusPaperService sqfwCenSusPaperService;

    @Inject("taskUpdateExecutor")
    private ThreadPoolExecutor taskUpdateExecutor;
    @Inject
    private PropertiesProxy propertiesProxy;
    @Inject
    private MeetingMinutesService meetingMinutesService;
    @Inject
    private SysLogService sysLogService;

    @Inject
    private MeetingMinutesComponent meetingMinutesComponent;

    @Inject
    private SqfwCheckRecordForAdminService sqfwCheckRecordForAdminService;

    @Inject
    private WasteClassificationService wasteClassificationService;

    @Inject(value = "jinYangStreetService")
    private SecurityInvestigationService jinYangStreetService;

    @Inject(value = "yunTanStreetService")
    private SecurityInvestigationService yunTanStreetService;

    @Inject(value = "youZhaStreetService")
    private SecurityInvestigationService youZhaStreetService;

    @Inject(value = "huaGuoYuanStreetService")
    private SecurityInvestigationService huaGuoYuanStreetService;
    @Inject
    private SqfwSummaryForAdminService sqfwSummaryForAdminService;

    @Inject
    private FromSummaryComponent fromSummaryComponent;

    @Inject
    private SqfwSmsMsgService sqfwSmsMsgService;
    @Inject
    private SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    private OldCareServiceStationExcelService oldCareServiceStationExcelService;
    @Inject
    private DaYingLuRedWhiteRecordExcelService daYingLuRedWhiteRecordExcelService;
    @Inject
    private DaYingLuRedWhiteRecordPdfService daYingLuRedWhiteRecordPdfService;

    @Inject
    private CenturyCitySecurityService centuryCitySecurityService;

    @Inject
    private PublicSecurityService publicSecurityService;

    @Inject
    private SafetyCheckExcelService safetyCheckExcelService;
    @Inject
    private SafetyCheckPdfService safetyCheckPdfService;
    @Inject
    private ZtSmsService ztSmsService;


    ExecutorService executorService = Executors.newFixedThreadPool(50);

    @Override
    public List<Map> queryPlaceInfoList(String unitId, String type, String checkPlaceName, String returnKey) {

        String userId = SecurityUtil.getUserId();
        Sys_user sysUser = sysUserService.fetch(userId);
        if (null == sysUser) return Lists.newArrayList();
        if (StringUtils.isBlank(returnKey)) returnKey = "a1";
        String sqlStr = buildSqlParam(sysUser, returnKey, type, checkPlaceName);

        Sql sql = Sqls.create(sqlStr);
        sql.setParam("returnKey", returnKey);
        sql.setParam("unitId", unitId);

        if (StringUtils.isNotBlank(checkPlaceName)) sql.setParam("unitName", "%" + checkPlaceName + "%");
        if (StringUtils.isNotBlank(type)) sql.setParam("type", type);
        String finalReturnKey = returnKey;
        sql.setCallback((Connection con, ResultSet rs, Sql sqlItem) -> {
            List<Map<String, Object>> list = Lists.newArrayList();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", StringUtils.isBlank(rs.getString(finalReturnKey)) ? "" : rs.getString(finalReturnKey));
                map.put("date", rs.getString("createDate"));
                list.add(map);
            }
            return list;
        });
        dao().execute(sql);


        return sql.getList(Map.class);
    }


    private String buildSqlParam(Sys_user sysUser, String returnKey, String type, String checkPlaceName) {
        //级别判断，省、市、区、街道、社区，从上往下
        String levelParam = "直属";
        String province = sysUser.getProvince();
        String city = sysUser.getCity();
        String district = sysUser.getDistrict();
        String county = sysUser.getCounty();
        String community = sysUser.getCommunity();
        StringBuilder sqlStr = new StringBuilder();

        sqlStr.append("select b.* from ( ");
        sqlStr.append(" select tp.").append(returnKey).append(" ,to_char( greatest(tp.create_date1,tp.create_date2,tp.create_date3,tp.create_date4,tp.create_date5),'yyyy年mm月dd日') as createDate from ( ");
        sqlStr.append(" select a.").append(returnKey).append(",");
        sqlStr.append(" (select sfs1.create_date from shequ.sqfw_form_summary sfs1 where sfs1.type=a.type and sfs1.").append(returnKey).append("= a.").append(returnKey).append(" and sfs1.province=a.province order by create_date desc limit 1 ) as create_date1,");
        sqlStr.append(" (select sfs2.create_date from shequ.sqfw_form_summary sfs2 where sfs2.type=a.type and sfs2.").append(returnKey).append("= a.").append(returnKey).append(" and sfs2.province=a.province and sfs2.city=a.city order by create_date desc limit 1 )  as create_date2,");
        sqlStr.append(" (select sfs3.create_date from shequ.sqfw_form_summary sfs3 where sfs3.type=a.type and sfs3.").append(returnKey).append("= a.").append(returnKey).append(" and sfs3.province=a.province and sfs3.city=a.city  and sfs3.district=a.district order by create_date desc limit 1 )  as create_date3,\n");
        sqlStr.append(" (select sfs4.create_date from shequ.sqfw_form_summary sfs4 where sfs4.type=a.type and sfs4.").append(returnKey).append("= a.").append(returnKey).append(" and sfs4.province=a.province and sfs4.city=a.city  and sfs4.district=a.district and sfs4.county=a.county order by create_date desc limit 1 )  as create_date4,\n");
        sqlStr.append(" (select sfs5.create_date from shequ.sqfw_form_summary sfs5 where sfs5.type=a.type and sfs5.").append(returnKey).append("= a.").append(returnKey).append(" and sfs5.province=a.province and sfs5.city=a.city  and sfs5.district=a.district and sfs5.county=a.county  and sfs5.community=a.community order by create_date desc limit 1 )  as create_date5\n");
        sqlStr.append(" from ( ");


        sqlStr.append(" SELECT type,province,city,district,county,community,create_date  , ").append(returnKey).append(" ,row_number() over(partition by ").append(returnKey).append(" order by create_date desc) as num FROM shequ.sqfw_form_summary where 1=1 ");

        //由于每个街道在数据库的存储字段不一样因此目前限制只能街道可上级查下，界别高于街道的目前先只能本单位查本单位
        if (!levelParam.equals(county)) {
            if (!levelParam.equals(province)) {
                sqlStr.append(" and province='").append(province).append("'");
            }
            if (!levelParam.equals(city)) {
                sqlStr.append(" and city='").append(city).append("'");
            }
            if (!levelParam.equals(district)) {
                sqlStr.append(" and district='").append(district).append("'");
            }

            sqlStr.append(" and county='").append(county).append("'");
           /* if (!levelParam.equals(county)) {
                sqlStr.append(" and county='").append(county).append("'");
            }*/
            if (!levelParam.equals(community)) {
                sqlStr.append(" and community='").append(community).append("'");
            }

        } else {
            sqlStr.append("  unit_id = @unitId");
        }

        if (StringUtils.isNotBlank(checkPlaceName)) {
            sqlStr.append(" and @returnKey like @unitName ");
        }
        if (StringUtils.isNotBlank(type)) {
            sqlStr.append(" and type = @type ");
        }
        sqlStr.append("  ) a where a.num=1  ");
        sqlStr.append(" )tp ) b order by b.createDate desc");
        return sqlStr.toString();


    }

    @Override
    public List<Map> listUnitPlaceName(String unitId, String type, String checkPlaceName, String returnKey) {

        if (StringUtils.isBlank(unitId)) return Lists.newArrayList();

        if (StringUtils.isBlank(returnKey)) returnKey = "a1";
        // 目前只针对场所进行查询
        /*String sqlStr = " SELECT DISTINCT " + returnKey + " FROM shequ.\"sqfw_form_summary\" where unit_id = @unitId ";
        if (StringUtils.isNotBlank(checkPlaceName)) sqlStr += " and @returnKey like @unitName ";
        if (StringUtils.isNotBlank(type)) sqlStr += " and type = @type ";

        Sql sql = Sqls.create(sqlStr);*/
        //zhangp 2023-12-12 调整sql查询
        String sqlStr = " SELECT id ,row_number() over(partition by " + returnKey + " order by create_date desc) as num FROM shequ.\"sqfw_form_summary\" where unit_id = @unitId ";
        if (StringUtils.isNotBlank(checkPlaceName)) sqlStr += " and @returnKey like @unitName ";
        if (StringUtils.isNotBlank(type)) sqlStr += " and type = @type ";

        String sqlStrTemp = "select a.id from (" + sqlStr + ") a where a.num=1 ";
        String sqlStrEnd = "select id,to_char(create_date,'yyyy年mm月dd日')  as createDate  ," + returnKey + " from shequ.sqfw_form_summary sfs where sfs.id in(" + sqlStrTemp + ") order by sfs.create_date desc  ";

        Sql sql = Sqls.create(sqlStrEnd);
        sql.setParam("returnKey", returnKey);
        sql.setParam("unitId", unitId);

        if (StringUtils.isNotBlank(checkPlaceName)) sql.setParam("unitName", "%" + checkPlaceName + "%");
        if (StringUtils.isNotBlank(type)) sql.setParam("type", type);
        String finalReturnKey = returnKey;
        sql.setCallback((Connection con, ResultSet rs, Sql sqlItem) -> {
            //List<String> list = Lists.newArrayList();
            List<Map<String, Object>> list = Lists.newArrayList();
            while (rs.next()) {
                //list.add(rs.getString(finalReturnKey));
                Map<String, Object> map = new HashMap<>();
                map.put("name", StringUtils.isBlank(rs.getString(finalReturnKey)) ? "" : rs.getString(finalReturnKey));
                map.put("date", rs.getString("createDate"));
                map.put("id", rs.getString("id"));
                list.add(map);
            }
            return list;
        });
        dao().execute(sql);
        return sql.getList(Map.class);
    }

    @Override
    public SqfwFormSummaryUnitInfoVO getUnitPlaceLatestInfoByName(String unitNameStr, String unitId, String conditionKey, String type) {
        String userId = SecurityUtil.getUserId();
        Sys_user sysUser = sysUserService.fetch(userId);
        if (null == sysUser) return null;
        //级别判断，省、市、区、街道、社区，从上往下
        String levelParam = "直属";
        String province = sysUser.getProvince();
        String city = sysUser.getCity();
        String district = sysUser.getDistrict();
        String county = sysUser.getCounty();
        String community = sysUser.getCommunity();
        if (StringUtils.isBlank(conditionKey)) conditionKey = "a1";

        Cnd cnd = Cnd.where(conditionKey, "=", unitNameStr);

        if (StringUtils.isNotBlank(type)) {
            cnd.and("type", "=", type);
        }
        //由于每个街道在数据库的存储字段不一样因此目前限制只能街道可上级查下，界别高于街道的目前先只能本单位查本单位
        if (!levelParam.equals(county)) {
            if (!levelParam.equals(province)) {
                cnd.and(" province ", "=", province);
            }
            if (!levelParam.equals(city)) {
                cnd.and(" city ", "=", city);
            }
            if (!levelParam.equals(district)) {
                cnd.and(" district ", "=", district);
            }
            cnd.and(" county ", "=", county);
            /*if (!levelParam.equals(county)) {
                cnd.and(" county ", "=", county);
            }*/
            if (!levelParam.equals(community)) {
                cnd.and(" community ", "=", community);
            }
        } else {
            cnd.and(" unit_id ", "=", unitId);
        }

        cnd.orderBy("fill_date", "desc");
        Sqfw_formSummary formSummary = fetch(cnd);

        SqfwFormSummaryUnitInfoVO unitInfoVO = new SqfwFormSummaryUnitInfoVO();
        BeanUtil.copyProperties(formSummary, unitInfoVO);
        return unitInfoVO;
    }

    @Override
    public SqfwFormSummaryUnitInfoVO getUnitPlaceLatestInfo(String unitNameStr, String unitId) {
        if (StringUtils.isBlank(unitId)) return null;
        Cnd cnd = Cnd.where("a1", "=", unitNameStr).and("unit_id", "=", unitId);
        cnd.orderBy("fill_date", "desc");
        Sqfw_formSummary formSummary = fetch(cnd);
        SqfwFormSummaryUnitInfoVO unitInfoVO = new SqfwFormSummaryUnitInfoVO();
        BeanUtil.copyProperties(formSummary, unitInfoVO);
        return unitInfoVO;
    }

    @Override
    public SqfwFormSummaryUnitInfoVO getUnitPlaceLatestInfo(String conditionKey, String placeName, String unitId) {
        if (StringUtils.isBlank(unitId)) return null;
        if (StringUtils.isBlank(conditionKey)) conditionKey = "a1";
        Cnd cnd = Cnd.where(conditionKey, "=", placeName).and("unit_id", "=", unitId);
        cnd.orderBy("fill_date", "desc");
        Sqfw_formSummary formSummary = fetch(cnd);
        SqfwFormSummaryUnitInfoVO unitInfoVO = new SqfwFormSummaryUnitInfoVO();
        BeanUtil.copyProperties(formSummary, unitInfoVO);
        return unitInfoVO;
    }


    @Override
    public SqfwFormSummaryUnitInfoVO getUnitPlaceLatestInfoById(String id) {
        Sqfw_formSummary formSummary = fetch(id);
        SqfwFormSummaryUnitInfoVO unitInfoVO = new SqfwFormSummaryUnitInfoVO();
        BeanUtil.copyProperties(formSummary, unitInfoVO);
        return unitInfoVO;
    }

    @Override
    public void generateFireHiddenPdf(String userId, SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {

        insertWordFlowAndFormSummary(userId, formSummaryWithFlow, SqfwFormSummaryConstants.safety_check);

        Sqfw_completeflow completeFlow = formSummaryWithFlow.getCompleteFlow();
        Sqfw_formSummary formSummary = formSummaryWithFlow.getFormSummary();

        executorService.execute(() -> {
            doGenerateFireHiddenPdf(completeFlow, formSummary, true);
        });
    }

    private void doGenerateFireHiddenPdf(Sqfw_completeflow completeFlow, Sqfw_formSummary formSummary, boolean sendMsgFlag) {
        boolean successFlag = false;
        String resourcePath = "";
        String sendMsgPhone = "";
        Sqfw_Sms_Msg smsMsg = null;

        try {
            String unitId = formSummary.getUnitId();
            Sys_unit unit = sysUnitService.fetch(unitId);

            FireHiddenCheckWordDTO wordDTO = new FireHiddenCheckWordDTO();
            BeanUtil.copyProperties(formSummary, wordDTO);
            wordDTO.setCompleteUnitName(unit.getName());
            wordDTO.setUnitName(unit.getName());

            GenerateWordAndPdfUrlVO wordVO = createFireHiddenCheckFormWordAndPDFByUnitName(wordDTO);
            if (StringUtils.isNotBlank(wordVO.getPdfUrl())) {
                resourcePath = wordVO.getPdfUrl();
                sendMsgPhone = wordVO.getPhone();
                sendMsgPhone = StringUtils.isBlank(sendMsgPhone) ? formSummary.getA8() : sendMsgPhone;
                successFlag = true;
                smsMsg = wordVO.getSmsMsg();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 生成完成之后更新工作流状态
        if (successFlag) completeFlow.setResourcePath(resourcePath);
        else completeFlow.setResourcePath("error");
        sqfwCompleteflowService.update(completeFlow);

        // 当生成完毕之后就直接发送webSocket消息或者短信消息
        sendMsgAfterFireHiddenPdfOrExcel(completeFlow.getUserId(), sendMsgPhone, sendMsgFlag, smsMsg);
    }

    @Override
    public void retryGenerateFireHiddenPdf(String userId, String sqfwFlowId) {
        // 首先根据工作流id查询到表单的数据
        Sqfw_completeflow sqfwCompleteFlow = sqfwCompleteflowService.fetch(sqfwFlowId);
        if (sqfwCompleteFlow == null) return;
        // 将工作流的pdf生成状态设置为creating
        sqfwCompleteFlow.setResourcePath("creating");
        sqfwCompleteflowService.update(sqfwCompleteFlow);

        // 然后组成相应的DTO 创建pdf
        Cnd cnd = Cnd.NEW().and("sqfw_flow_id", "=", sqfwFlowId);
        Sqfw_formSummary formSummaryOfFlow = fetch(cnd);

        executorService.execute(() -> {
            doGenerateFireHiddenPdf(sqfwCompleteFlow, formSummaryOfFlow, false);
        });
    }

    /**
     * 重新生成应急 （拆分pdf）
     *
     * @param ids
     * @param isAll 如果为ture，则全部重新生成
     */
    @Override
    public void retryGenerateFireHiddenPdfs(List<String> ids, boolean isAll, Integer... pages) {
        // 重新生成应急 （拆分pdf）
        int page = 0, size = 100;
        List<Sqfw_formSummary> formSummaryList;
        if (isAll) {
            if (pages.length > 0) {
                page = pages[0];
            }
            String sql = "select * from shequ.sqfw_form_summary WHERE" +
                    " county='" + StreetEnum.WEI_QING_MEN_STREET.getName() + "' AND " +
                    "type='" + SqfwFormSummaryConstants.safety_check + "'" +
                    " and a61 is not null " +
                    " limit " + size + " offset " + page;
            formSummaryList = this.listEntity(Sqls.create(sql));
        } else {
            Cnd cnd = Cnd.NEW();
            cnd.and("id", "in", ids);
            formSummaryList = query(cnd);
        }

        for (Sqfw_formSummary formSummary : formSummaryList) {
            String unitId = formSummary.getUnitId();
            Sys_unit unit = sysUnitService.fetch(unitId);
            if (unit == null) {
                continue;
            }
            FireHiddenOfficeWordDTO wordDTO = new FireHiddenOfficeWordDTO();
            BeanUtil.copyProperties(formSummary, wordDTO);
            wordDTO.setCompleteUnitName(unit.getName());
            wordDTO.setUnitName(unit.getName());
            Sys_user sysUser = null;
            try {
                sysUser = sysUserService.getUserById(wordDTO.getCreateBy());
            } catch (BaseException e) {
                continue;
            }
            wordDTO.setCreateUserName(sysUser.getUsername());
            wordDTO.setProvince(sysUser.getProvince());
            wordDTO.setCity(sysUser.getCity());
            wordDTO.setDistrict(sysUser.getDistrict());
            wordDTO.setCounty(sysUser.getCounty());
            wordDTO.setCommunity(sysUser.getCommunity());

            //获取上一次的巡查
            Cnd c = Cnd.NEW();
            c.and("unit_id", "=", formSummary.getUnitId())
                    .and("a1", "=", formSummary.getA1())
                    .and("sqfw_id", "=", formSummary.getSqfwId())
                    .and("fill_date", "<", formSummary.getFillDate());
            c.orderBy("fill_date", "desc");
            Sqfw_formSummary f = fetch(c);
            FireHiddenOfficeWordDTO upFormSummary = new FireHiddenOfficeWordDTO();
            BeanUtil.copyProperties(f, upFormSummary);
            wordDTO.setUpFormSummary(f != null ? upFormSummary : null);

            FireHiddenOfficeFactory.createSplitPdf(wordDTO);
        }

        while (formSummaryList.size() == size) {
            retryGenerateFireHiddenPdfs(ids, isAll, page + size - 1);
        }
    }

    /**
     * 根据服务记录id生成消防安全excel数据
     *
     * @param sqfwId      服务记录id
     * @param workOrderId 工单id
     * @param userId      用户id
     * @param fileIndex   文件索引
     * @return excel文件链接
     */
    @Override
    public String generateFireHiddenCollectionExcelForApp(String sqfwId, String workOrderId, String userId, Integer fileIndex) {
        if (StringUtils.isBlank(sqfwId)) return null;
        return generateFireHiddenCollectionExcelForApp(Lists.newArrayList(sqfwId), workOrderId, userId, fileIndex, null, null, null);
    }

    private String generateFireHiddenCollectionExcelForApp(List<String> sqfwIdList, String workOrderId, String userId, Integer fileIndex, String fileNameSuffix, String isTemplate, String street) {
        if (StringUtils.isBlank(isTemplate)) {
            if (sqfwIdList.size() == 0) return null;
        }

        // 短信下载
        if (fileIndex == 400) {
            return sqfwSmsMsgService.downExcel(sqfwIdList.get(0));
        }

        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", sqfwIdList);

        if (StringUtils.isNotBlank(workOrderId)) {
            cnd.and("work_order_id", "=", workOrderId);
        }

        cnd.orderBy("fill_date", "asc");

        List<Sqfw_formSummary> formSummaryList = query(cnd);

        //zhangp  2024-01-04 web端下载模板时没数据，定制化服务街道由前端传入，表头需要固定
        String unitName = street;
        Sqfw_servicerecord serviceRecord = new Sqfw_servicerecord();
        AbstractExcelParamDTO excelParamDTO = new AbstractExcelParamDTO();
        excelParamDTO.setFillDate(new Date());
        excelParamDTO.setSignalPersonImgUrl("");

        if (StringUtils.isBlank(isTemplate)) {
            // wzy 2023-11-15 如果一条填写的数据都没有则提示“暂无数据，不能生成Excel”
            if (formSummaryList.size() == 0) throw new ServiceException("暂无数据，不能生成Excel");
            excelParamDTO.setFormSummaryList(formSummaryList);
        } else {
            //模板下载时数据置空
            excelParamDTO.setFormSummaryList(Lists.newArrayList());
            excelParamDTO.setUnitNamePrefix(unitName);
            excelParamDTO.setCompleteUnitName(unitName);
        }
        if (!sqfwIdList.isEmpty()) {
            String sqfwId = sqfwIdList.get(0);
            serviceRecord = sqfwServicerecordService.fetch(sqfwId);


            excelParamDTO.setUnitNamePrefix(serviceRecord.getCompanyName());
            excelParamDTO.setCompleteUnitName(serviceRecord.getCompanyName());

            Sys_user createServiceRecordUser = sysUserService.getUserById(serviceRecord.getUser_id());
            String unitId = createServiceRecordUser.getUnitId();
            Sys_unit unit = sysUnitService.getMasterCompany(unitId);

            unitName = unit.getName();
        }
        /*
        String sqfwId = sqfwIdList.get(0);
        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);

        AbstractExcelParamDTO excelParamDTO = new AbstractExcelParamDTO();
        excelParamDTO.setFillDate(new Date());
        excelParamDTO.setSignalPersonImgUrl("");
        excelParamDTO.setUnitNamePrefix(serviceRecord.getCompanyName());
        excelParamDTO.setCompleteUnitName(serviceRecord.getCompanyName());

        excelParamDTO.setFormSummaryList(formSummaryList);

        Sys_user createServiceRecordUser = sysUserService.getUserById(serviceRecord.getUser_id());
        String unitId = createServiceRecordUser.getUnitId();
        Sys_unit unit = sysUnitService.getMasterCompany(unitId);

        String unitName = unit.getName();
        */
        // 油榨街街道的
        if (unitName.contains("油榨街")) {
            excelParamDTO.setFileNameSuffix(fileNameSuffix);
            return FireHiddenOfficeUtils.createFireHiddenExcelYouZhaJieShiNanSQ(excelParamDTO, isTemplate);
        }

        // 金元社区的
        if (unitName.contains("金元") || unitName.contains("润兴") || unitName.contains("金阳")) {
            Sys_user createFileUser = sysUserService.fetch(userId);

            FireHiddenExcelParamJinYuanSQDTO dto = new FireHiddenExcelParamJinYuanSQDTO();
            BeanUtil.copyProperties(excelParamDTO, dto);

            if (unitName.contains("金元")) {
                dto.setVisAndInsExcelTitlePrefix(StrFormatter.format("金阳街道金元社区九小场所{}", DateUtil.format(dto.getFillDate(), "yyyy年MM月")));
                dto.setGasInsExcelTitlePrefix("金阳街道金元社区");
                dto.setGasRecExcelTitlePrefix("观山湖区金元社区");
                dto.setFireSafetyExcelTitlePrefix("金阳街道金元社区");
            }

            if (unitName.contains("润兴")) {
                dto.setVisAndInsExcelTitlePrefix(StrFormatter.format("金阳街道润兴居委会{}", DateUtil.format(dto.getFillDate(), "yyyy年MM月")));
                dto.setGasInsExcelTitlePrefix("金阳街道润兴居委会");
                dto.setGasRecExcelTitlePrefix("观山湖区润兴居委会");
                dto.setFireSafetyExcelTitlePrefix("金阳街道润兴居委会");
            }

            dto.setCreateUserName(createFileUser.getUsername());
            dto.setCreateUserPhone(createFileUser.getLoginname());
            dto.setCompleteUnitName(unitName);

            if (fileIndex == null) fileIndex = 1;
            dto.setFileIndex(fileIndex);

            // 如果是生成台账，则需要查询一些数据用来进行填装
            if (fileIndex == 0 || fileIndex == 4) {
                List<Sqfw_formSummary> jinYuanFormSummaryList = dto.getFormSummaryList();

                Map<String, Sqfw_formSummary> latestA1AndA13Map = Maps.newHashMap();
                for (Sqfw_formSummary jinYuanFormSummary : jinYuanFormSummaryList) {
                    String jinYuanA1 = jinYuanFormSummary.getA1();
                    String jinYuanA13 = jinYuanFormSummary.getA13();

                    if (jinYuanA13.equals("整改完成")) {
                        Cnd jinYuanCnd = Cnd.NEW();
                        jinYuanCnd.and(Sqfw_formSummary::getA1, "=", jinYuanA1)
                                .and(Sqfw_formSummary::getA13, "=", "有")
                                .and(Sqfw_formSummary::getUnitId, "=", jinYuanFormSummary.getUnitId());
                        jinYuanCnd.orderBy(Sqfw_formSummary::getFillDate, "desc");
                        Sqfw_formSummary jinYuanQueryFormSummary = fetch(jinYuanCnd);
                        if (jinYuanQueryFormSummary != null && !jinYuanQueryFormSummary.getId().equals(jinYuanFormSummary.getId()))
                            latestA1AndA13Map.put(jinYuanQueryFormSummary.getA1(), jinYuanQueryFormSummary);
                    }

                }
                dto.setLatestA1AndA13Map(latestA1AndA13Map);
            }

            // 生成文件
            excelParamDTO.setFileNameSuffix(fileNameSuffix);
            VisAndInsForJinYangJieDaoExcelVO jinYuanFireHiddenExcelVO = FireHiddenOfficeUtils.createFireHiddenExcelJinYuanSQ(dto, isTemplate);
            if (jinYuanFireHiddenExcelVO.getErrorStatus()) return null;

            if (fileIndex == 1) return jinYuanFireHiddenExcelVO.getVisAndInsExcelUrl();
            if (fileIndex == 2) return jinYuanFireHiddenExcelVO.getGasInsExcelUrl();
            if (fileIndex == 3) return jinYuanFireHiddenExcelVO.getGasRecExcelUrl();
            if (fileIndex == 4) return jinYuanFireHiddenExcelVO.getStandingBookExcelUrl();

            if (fileIndex == 0)
                return StrFormatter.format("{},{},{},{}", jinYuanFireHiddenExcelVO.getVisAndInsExcelUrl(),
                        jinYuanFireHiddenExcelVO.getGasInsExcelUrl(), jinYuanFireHiddenExcelVO.getGasRecExcelUrl(), jinYuanFireHiddenExcelVO.getStandingBookExcelUrl());
        }

        //大营路街道
        if (unitName.contains("大营路街道")) {
            Sys_user createFileUser = sysUserService.fetch(userId);
            FireHiddenExcelParamDaYingLuSQDTO dto = new FireHiddenExcelParamDaYingLuSQDTO();
            BeanUtil.copyProperties(excelParamDTO, dto);
            dto.setStreet(createFileUser.getCounty());
            dto.setCreateUserName(createFileUser.getUsername());
            dto.setCreateUserPhone(createFileUser.getLoginname());
            dto.setFileIndex(fileIndex);
            dto.setCompleteUnitName(unitName);
            dto.setArea(serviceRecord.getDistrict());
            dto.setStreet(serviceRecord.getCounty());

            List<Sqfw_formSummary> preFormSummaryList = dto.getFormSummaryList();
            Map<String, Sqfw_formSummary> lastFormSummaryCheckMap = Maps.newHashMap();
            for (Sqfw_formSummary formSummary : preFormSummaryList) {
                Cnd dylLastCheckCND = Cnd.NEW();
                dylLastCheckCND.and(Sqfw_formSummary::getA1, "=", formSummary.getA1())
                        .and(Sqfw_formSummary::getUnitId, "=", formSummary.getUnitId());
                dylLastCheckCND.orderBy(Sqfw_formSummary::getFillDate, "desc");
                Sqfw_formSummary lastCheckFormSummary = fetch(dylLastCheckCND);
                if (lastCheckFormSummary != null && !lastCheckFormSummary.getId().equals(formSummary.getId())) {
                    lastFormSummaryCheckMap.put(formSummary.getId(), lastCheckFormSummary);
                }
            }
            dto.setLastFormSummaryCheckMap(lastFormSummaryCheckMap);
            return DaYingLuStreetFireHiddenExcelUtils.createFireHiddenExcelDaYingLuSQ(dto, isTemplate);
        }

        /**
         * ywm
         */
        FireHiddenExcelParamSQDTO excelParamSQDTO = new FireHiddenExcelParamSQDTO();
        BeanUtil.copyProperties(excelParamDTO, excelParamSQDTO);
        excelParamSQDTO.setUserId(userId);
        excelParamSQDTO.setFileIndex(fileIndex);
        excelParamSQDTO.setCompleteUnitName(unitName);
        Sys_user user = sysUserService.getUserById(userId);
        excelParamSQDTO.setCity(user.getCity());
        excelParamSQDTO.setCounty(user.getCounty());
        excelParamSQDTO.setProvince(user.getProvince());
        excelParamSQDTO.setCommunity(user.getCommunity());
        excelParamSQDTO.setDistrict(user.getDistrict());
        String url;

        if (unitName.contains(StreetEnum.YUN_TAN_STREET.getName())) {
            url = new YuHongFireHiddenExcel().createExcel(excelParamSQDTO, isTemplate);
        } else {
            if ("isTemplate".equals(isTemplate)) {
                url = FireHiddenExcelFactory.downExcelTemplate(excelParamSQDTO);
            } else {
                url = FireHiddenExcelFactory.createExcel(excelParamSQDTO);
            }
        }
        if (!"null".equals(url)) {
            return url;
        }

        // 其他社区的
        return FireHiddenOfficeUtils.createFireHiddenExcel(excelParamDTO, isTemplate);

    }

    @Override
    public Integer sendFireHiddenPeersMsg(FireHiddenPeersMsgDTO dto) {

        // wzy 2023-12-15 暂时取消消防安全同行人接口
        //String fromUserName = dto.getFromUserName();
        //String toUserPhone = dto.getToUserPhone();
        //if (StringUtils.isBlank(toUserPhone) || StringUtils.isBlank(fromUserName)) return 0;
        //
        //String msgContent = StrFormatter.format("请知悉：{} {}在{}任务中，检查{}时，将你添加为同行人",
        //        DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"), fromUserName, dto.getServiceType(), dto.getA1());
        //SmsMsgDTO smsMsgDTO = new SmsMsgDTO();
        //smsMsgDTO.setPhoneNumberSet(Sets.newHashSet(toUserPhone.split(",")));
        //smsMsgDTO.setTemplateParamList(Lists.newArrayList(msgContent));
        //return opaSmsService.opaSmsSendOneMessage(smsMsgDTO);
        return 1;
    }

    @Override
    public String generateAppointPdfConverge(String sqfwId, String workOrderId, String fileType) {
//        if (StringUtils.isBlank(sqfwId)) return null;
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isEmpty(sqfwId)) {
            List<Sqfw_formSummary_new> formSummaryNews = CommonComponent.querySummarys(null, fileType);
            if (CollectionUtil.isNotEmpty(formSummaryNews)) {
                List<String> sqfwIds = formSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwId).collect(Collectors.toList());
                cnd.and("sqfw_id", "in", sqfwIds);
            }
        }

        if (StringUtils.isNotEmpty(sqfwId)) {
            cnd.and("sqfw_id", "=", sqfwId);
        }

        if (StringUtils.isBlank(fileType)) fileType = SqfwFormSummaryConstants.safety_check;
        cnd.and("file_type", "=", fileType);

        if (StringUtils.isNotBlank(workOrderId))
            cnd.and("worker_id", "=", workOrderId);

        cnd.orderBy("create_date", "asc");
        List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.query(cnd);
        if (completeFlowList.size() == 0) return null;

        List<String> pdfList = completeFlowList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());

        try {
            String fileName = "";
            if (StringUtils.isNotBlank(fileType)) {
                if (SqfwFormSummaryConstants.public_security.equals(fileType)) {
                    fileName = DownLoadFileNameEnum.DYL_PUBLIC_SECURITY_STANDING_PDF.getName();
                } else if (SqfwFormSummaryConstants.house_survey_form.contains(fileType)) {
                    fileName = DownLoadFileNameEnum.HOME_REGISTRATION_PDF.getName();
                } else if (SqfwFormSummaryConstants.refuse_classify.contains(fileType)) {
                    fileName = DownLoadFileNameEnum.RUBBISH_CLASS_PDF.getName();
                } else if (SqfwFormSummaryConstants.meeting_record.contains(fileType)) {
                    fileName = DownLoadFileNameEnum.MEETING_RECORD_PDF.getName();
                } else if (SupportBusinessTypeEnum.CHILDREN_VISITATION.getName().equals(fileType)) {
                    fileName = "【" + SupportBusinessTypeEnum.CHILDREN_VISITATION.getName() + "】合集";
                } else {
                    //fileName = "pdf" + fileType + "整治表集合";
                    fileName = DownLoadFileNameEnum.SAFETY_INVESTIGATE_RENOVATE.getName();
                }
            }
            return createConvergePdfAndUpload(pdfList, fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    public String generateAppointPdfConverge(String userId, String sqfwId, String workOrderId, String fileType, int index) {
        if (StringUtils.isBlank(sqfwId)) return null;

        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "=", sqfwId);

        if (StringUtils.isBlank(fileType)) fileType = SqfwFormSummaryConstants.safety_check;
        cnd.and("type", "=", fileType);

        if (StringUtils.isNotBlank(workOrderId))
            cnd.and("work_order_id", "=", workOrderId);

        cnd.orderBy("create_date", "asc");
        List<Sqfw_formSummary> summaryList = this.query(cnd);

        if (summaryList.size() > 0) {
            Sys_user user = sysUserService.getUserById(userId);
            List<String> ids = summaryList.stream().map(Sqfw_formSummary::getId).collect(Collectors.toList());
            String path = GeneratePdfConverge.downPdfConverge(user.getUnitName(), ids, index);
            return path;
        }
        return null;
    }

    @Override
    public void generateRefuseClassifyPdf(String userId, SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {

        insertWordFlowAndFormSummary(userId, formSummaryWithFlow, SqfwFormSummaryConstants.refuse_classify);

        Sqfw_completeflow completeFlow = formSummaryWithFlow.getCompleteFlow();
        Sqfw_formSummary formSummary = formSummaryWithFlow.getFormSummary();

        executorService.execute(() -> generateRefuseClassifyPDFByFlowAndForm(userId, completeFlow, formSummary));
    }

    @Override
    public String generateRefuseClassifyExcelForApp(String sqfwId) {
        if (StringUtils.isBlank(sqfwId)) return null;
        return generateRefuseClassifyExcelForApp(Lists.newArrayList(sqfwId), null);
    }

    private String generateRefuseClassifyExcelForApp(List<String> sqfwIdList, String fileNameSuffix) {
        if (sqfwIdList.size() == 0) return null;
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", sqfwIdList).and("type", "=", SqfwFormSummaryConstants.refuse_classify);
        cnd.orderBy("fill_date", "asc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);

        // wzy 2023-11-15 如果一条数据都没有则不能生成
        if (formSummaryList.size() == 0) throw new ServiceException("暂无数据，不能生成Excel");

        String sqfwId = sqfwIdList.get(0);
        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);

        RefuseClassifyExcelParamDTO excelParamDTO = new RefuseClassifyExcelParamDTO();
        excelParamDTO.setFillDate(new Date());
        excelParamDTO.setSignalPersonImgUrl("");
        excelParamDTO.setAreaLevel(serviceRecord.getCounty() + serviceRecord.getCommunity());
        excelParamDTO.setCompleteUnitName(serviceRecord.getCompanyName());

        excelParamDTO.setFormSummaryList(formSummaryList);
        try {
            excelParamDTO.setFileNameSuffix(fileNameSuffix);
            return RefuseClassifyOfficeUtils.createRefuseClassifyExcel(excelParamDTO, null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void retryGenerateRefuseClassifyPdf(String userId, String sqfwFlowId) {
        // 首先根据工作流id查询到表单的数据
        Sqfw_completeflow sqfwCompleteFlow = sqfwCompleteflowService.fetch(sqfwFlowId);
        if (sqfwCompleteFlow == null) return;
        String resourcePath = sqfwCompleteFlow.getResourcePath();
        if (resourcePath.contains("/")) return;  // 说明之前是创建成功的
        // 将工作流的pdf生成状态设置为creating
        sqfwCompleteFlow.setResourcePath("creating");
        sqfwCompleteflowService.update(sqfwCompleteFlow);

        // 然后组成相应的DTO 创建pdf
        Cnd cnd = Cnd.NEW().and("sqfw_flow_id", "=", sqfwFlowId);
        Sqfw_formSummary formSummaryOfFlow = fetch(cnd);

        executorService.execute(() -> generateRefuseClassifyPDFByFlowAndForm(userId, sqfwCompleteFlow, formSummaryOfFlow));
    }


    // ------------------------------------------------------------------------------
    //  生成入户调查表数据
    // ------------------------------------------------------------------------------

    /**
     * 根据户号和栋号查询信息
     *
     * @param a5 户号
     * @param a4 栋号
     * @return 结果
     */
    @Override
    public List<HouseSurveyFormPlaceVO> listPlaceForHouseSurveyFrom(String unitId, String workOrderId, String userId, String a5, String a4, String a3, String a1) {

        List<HouseSurveyFormPlaceVO> resultList = Lists.newArrayList();

        if (StringUtils.isBlank(unitId)) return resultList;

        Cnd cnd = Cnd.NEW();
        cnd.and("unit_id", "=", unitId).and("type", "=", SqfwFormSummaryConstants.house_survey_form)
                .and("create_by", "=", userId).and("work_order_id", "=", workOrderId);
        cnd.orderBy("fill_date", "desc");
        cnd.limit(1, 1);
        Sqfw_formSummary tempLastSurveyForm = fetch(cnd);

        Sqfw_formSummary lastSurveyForm = null;
        if (tempLastSurveyForm != null) {

            String tempQueryA1 = tempLastSurveyForm.getA1();
            String tempQueryA4 = tempLastSurveyForm.getA4();

            if (StringUtils.isNotBlank(a4) && StringUtils.isNotBlank(tempLastSurveyForm.getA4())
                    && !a4.equals(tempLastSurveyForm.getA4())) {
                tempQueryA4 = a4;
            }

            if (StringUtils.isNotBlank(a1) && StringUtils.isNotBlank(tempLastSurveyForm.getA1())
                    && !a1.equals(tempLastSurveyForm.getA1())) {
                tempQueryA1 = a1;
            }

            Cnd lastSurveyCnd = Cnd.NEW();
            lastSurveyCnd.and("unit_id", "=", unitId).and("type", "=", SqfwFormSummaryConstants.house_survey_form);
            lastSurveyCnd.and("a1", "like", StrFormatter.format("%{}%", tempQueryA1));
            if (tempLastSurveyForm.getA4() != null) lastSurveyCnd.and("a4", "=", tempQueryA4);
            lastSurveyCnd.and("a5", "like", StrFormatter.format("%{}%", a5));
            lastSurveyCnd.orderBy("fill_date", "desc");
            lastSurveyForm = fetch(lastSurveyCnd);
        }

        // 用于从第二部分查询中去除第一部分存在的数据
        String lastSurveyConditionKey = "";
        if (lastSurveyForm != null)
            lastSurveyConditionKey = StrFormatter.format("{},{},{}", lastSurveyForm.getA1(), lastSurveyForm.getA4(), lastSurveyForm.getA5());

        // 这个方法的逻辑就是根据a5查到上一次这个人填写的a5的信息，然后其余的就按照校区院落的字母 栋数 门牌号大小排序
        Cnd otherCnd = Cnd.NEW();
        otherCnd.and("unit_id", "=", unitId).and("type", "=", SqfwFormSummaryConstants.house_survey_form);
        otherCnd.and("a5", "like", StrFormatter.format("%{}%", a5));
        if (StringUtils.isNotBlank(a4)) otherCnd.and("a4", "like", StrFormatter.format("%{}%", a4));
        if (StringUtils.isNotBlank(a3)) otherCnd.and("a3", "=", a3);
        if (StringUtils.isNotBlank(a1)) otherCnd.and("a1", "like", StrFormatter.format("%{}%", a1));
        otherCnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> otherSurveyFormList = query(otherCnd);
        Map<String, Sqfw_formSummary> filterMap = Maps.newHashMap();
        for (Sqfw_formSummary formSummary : otherSurveyFormList) {
            String conditionKey = StrFormatter.format("{},{},{}", formSummary.getA1(), formSummary.getA4(), formSummary.getA5());
            if (filterMap.containsKey(conditionKey)) continue;

            filterMap.put(conditionKey, formSummary);
        }

        List<HouseSurveyFormPlaceVO> tempResultList = Lists.newArrayList();
        List<HouseSurveyFormPlaceVO> noA4List = Lists.newArrayList();

        for (String conditionKey : filterMap.keySet()) {
            Sqfw_formSummary formSummary = filterMap.get(conditionKey);

            if (lastSurveyForm != null && conditionKey.equals(lastSurveyConditionKey)) continue;

            HouseSurveyFormPlaceVO placeVO = new HouseSurveyFormPlaceVO();
            BeanUtil.copyProperties(formSummary, placeVO);

            if (StringUtils.isNotBlank(formSummary.getA1())) {
                placeVO.setA1Char(PinyinUtil.getFirstLetter(formSummary.getA1(), ""));
            } else {
                placeVO.setA1Char("");
            }

            if (StringUtils.isBlank(placeVO.getA4())) noA4List.add(placeVO);
            else tempResultList.add(placeVO);
        }

        // 首先按照a1排序  然后按照a4排序 然后按照a5排序
        tempResultList = tempResultList.stream().sorted(
                Comparator.comparing(HouseSurveyFormPlaceVO::getA1Char)
                        .thenComparing(HouseSurveyFormPlaceVO::getA4)
                        .thenComparing(HouseSurveyFormPlaceVO::getA5)
        ).collect(Collectors.toList());

        noA4List = noA4List.stream().sorted(
                Comparator.comparing(HouseSurveyFormPlaceVO::getA1Char)
                        .thenComparing(HouseSurveyFormPlaceVO::getA5)
        ).collect(Collectors.toList());

        if (lastSurveyForm != null) {
            HouseSurveyFormPlaceVO lastPlaceVO = new HouseSurveyFormPlaceVO();
            BeanUtil.copyProperties(lastSurveyForm, lastPlaceVO);
            if (StringUtils.isBlank(lastSurveyForm.getA1())) {
                lastPlaceVO.setA1Char("");
            } else {
                lastPlaceVO.setA1Char(PinyinUtil.getFirstLetter(lastSurveyForm.getA1(), ""));
            }
            resultList.add(lastPlaceVO);
        }

        resultList.addAll(tempResultList);
        resultList.addAll(noA4List);
        return resultList;
    }

    /**
     * 生成入户调查表数据
     *
     * @param formSummaryWithFlow 表单数据
     */
    @Override
    public void generateHouseSurveyFormPdf(SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        String userId = SecurityUtil.getUserId();
        insertWordFlowAndFormSummary(userId, formSummaryWithFlow, SqfwFormSummaryConstants.house_survey_form);
        Sqfw_completeflow completeFlow = formSummaryWithFlow.getCompleteFlow();
        Sqfw_formSummary formSummary = formSummaryWithFlow.getFormSummary();

        executorService.execute(() -> generateHouseSurveyFormPDFByFlowAndForm(userId, completeFlow, formSummary));
    }

    @Override
    public List<String> getDownloadHouseSurveyFormExcelType(String sqfwId, String isAdmin) {
        // 1 组装查询条件
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(isAdmin)) {
            if (StringUtils.isNotBlank(sqfwId)) {
                cnd.and("id", "in", Lists.newArrayList(sqfwId.split(",")));
            }
        } else {
            cnd.and(Sqfw_formSummary::getSqfwId, CommonConstants.EQUAL, sqfwId);
        }
        cnd.and(Sqfw_formSummary::getType, CommonConstants.EQUAL, SqfwFormSummaryConstants.house_survey_form);
        // 2 查询数据
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        if (formSummaryList.size() == 0) return Collections.emptyList();
        // 3 返回结果集
        List<String> resultList = Lists.newArrayList();
        List<String> a16s = formSummaryList.stream().map(Sqfw_formSummary::getA16).distinct().collect(Collectors.toList());
        boolean isIncludeDx = false;
        for (String a16 : a16s) {
            // 检查是否存在冬巡或者入户安全巡查 如果存在则添加：进家入户宣传台账
            if (!isIncludeDx) {
                if (StringUtils.isNotEmpty(a16) && (a16.contains(HouseSurveyEnum.WINTER_PARTROL.getName()) || a16.contains("冬巡"))) {
                    isIncludeDx = true;
                }
            }
            resultList.addAll(Arrays.asList(a16.split(",")));
        }
        if (isIncludeDx) {
            resultList.add(HouseSurveyEnum.HOME_PROMOTION_LEDGER.getName());
        }
        List<String> a7s = formSummaryList.stream().map(Sqfw_formSummary::getA7).distinct().collect(Collectors.toList());
        // 添加默认元素
        for (String a7 : a7s) {
            if (StringUtils.isEmpty(a7)) {
                continue;
            }
            List<Sqfw_cenSusPaper> cenPeopleList = JSONObject.parseArray(a7, Sqfw_cenSusPaper.class);
            for (Sqfw_cenSusPaper cenPeople : cenPeopleList) {
                if (StringUtils.isBlank(cenPeople.getId())) continue;
                String specialMark = cenPeople.getSpecialMark();
                if (StringUtils.isNotBlank(specialMark) && !specialMark.equals("否")) {
                    resultList.add(HouseSurveyEnum.SIX_TYPES_PERSON_LEDGER.getName());
                    resultList.add(HouseSurveyEnum.SIX_KEYNOTE_TABLE_STATIS.getName());
                    break;
                }
            }
            if (resultList.contains(HouseSurveyEnum.SIX_TYPES_PERSON_LEDGER.getName())) {
                break;
            }
        }
        //resultList.add(HouseSurveyEnum.SIX_TYPES_PERSON_LEDGER.getName());
        resultList.removeIf(a -> a.equals(HouseSurveyEnum.WINTER_PARTROL.getName()) || a.equals("冬巡"));
        // 去重后返回
        resultList = resultList.stream().distinct().collect(Collectors.toList());

        return resultList;
    }

    /**
     * 按照类型生成入户调查表excel
     *
     * @param sqfwId    社区服务id
     * @param excelType excel类型
     * @return excel链接
     */
    @Override
    public String generateHouseSurveyFormExcelForApp(String sqfwId, String excelType) {
        if (StringUtils.isBlank(sqfwId)) {
            throw new AppException("业务异常[请求参数不能为空]");
        }
        return generateHouseSurveyFormExcelForApp(Lists.newArrayList(sqfwId), excelType, null);
    }

    private String generateHouseSurveyFormExcelForApp(List<String> sqfwIdList, String excelType, String fileNameSuffix) {
        /*
        // wzy 2023-10-11 临时处理垃圾分类改为垃圾分类宣传
        String tempExcelType = excelType;
        if (tempExcelType.equals("垃圾分类")) tempExcelType = "垃圾分类宣传";*/

        if (sqfwIdList.size() == 0) return null;
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", sqfwIdList).and("type", "=", SqfwFormSummaryConstants.house_survey_form);
        cnd.orderBy("fill_date", "asc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        return CommonComponent.generateHouseSurveyFormExcelForApp(null, formSummaryList, excelType, fileNameSuffix, null, null, null);
    }

    /**
     * 入户调查 冬巡 生成人员家属信息
     *
     * @param excelParamDTO dto
     */
    private void getHouseSurveyExcelFamilyMemberInfo(HouseSurveyFormExcelParamDTO excelParamDTO) {
        List<Sqfw_formSummary> formSummaryList = excelParamDTO.getFormSummaryList();

        Map<String, List<Sqfw_cenSusPaper>> cenSusPaperMap = Maps.newHashMap();
        for (Sqfw_formSummary formSummary : formSummaryList) {
            String a7 = formSummary.getA7();
            if (StringUtils.isNotBlank(a7)) {
                List<Sqfw_cenSusPaper> a7CenSusPaperList = JSONObject.parseArray(a7, Sqfw_cenSusPaper.class);

                for (Sqfw_cenSusPaper susPaper : a7CenSusPaperList) {
                    if (StringUtils.isBlank(susPaper.getId())) {
                        cenSusPaperMap.put(susPaper.getId(), Lists.newArrayList());
                        continue;    // 为了防止脏数据id为空问题
                    }
                    List<Sqfw_cenSusPaper> familyMemberList = Lists.newArrayList();
                    for (Sqfw_cenSusPaper member : a7CenSusPaperList) {
                        if (StringUtils.isBlank(member.getId())) continue;    // 为了防止脏数据id为空问题
                        if (!susPaper.getId().equals(member.getId())) familyMemberList.add(member);
                    }
                    cenSusPaperMap.put(susPaper.getId(), familyMemberList);
                }
            }
        }
        excelParamDTO.setFamilyMemberInfoMap(cenSusPaperMap);
    }

    /**
     * 重新生成入户调查表PDF
     *
     * @param sqfwFlowId 工作流id
     */
    @Override
    public void retryGenerateHouseSurveyFormPdf(String userId, String sqfwFlowId) {
        // 首先根据工作流id查询到表单的数据
        Sqfw_completeflow sqfwCompleteFlow = sqfwCompleteflowService.fetch(sqfwFlowId);
        if (sqfwCompleteFlow == null) return;
        String resourcePath = sqfwCompleteFlow.getResourcePath();
        if (resourcePath.contains("/")) return;  // 说明之前是创建成功的
        // 将工作流的pdf生成状态设置为creating
        sqfwCompleteFlow.setResourcePath("creating");
        sqfwCompleteflowService.update(sqfwCompleteFlow);

        // 然后组成相应的DTO 创建pdf
        Cnd cnd = Cnd.NEW().and("sqfw_flow_id", "=", sqfwFlowId);
        Sqfw_formSummary formSummaryOfFlow = fetch(cnd);

        executorService.execute(() -> generateHouseSurveyFormPDFByFlowAndForm(userId, sqfwCompleteFlow, formSummaryOfFlow));
    }

    @Override
    public List<HouseSurveyFormPlaceVO> listSecondHouseSurvey(String sqfwId, String userId) {
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "=", sqfwId)
                .and("create_by", "=", userId)
                .and("type", "=", SqfwFormSummaryConstants.house_survey_form);
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> queryList = query(cnd);

        List<HouseSurveyFormPlaceVO> resultList = Lists.newArrayList();
        List<HouseSurveyFormPlaceVO> noA4List = Lists.newArrayList();
        Set<String> existedPlaceSet = Sets.newHashSet();
        for (Sqfw_formSummary formSummary : queryList) {

            String placeKey = StrFormatter.format("{},{},{}", formSummary.getA1(), formSummary.getA4(), formSummary.getA5());

            Set<String> a17ConditionSet = Sets.newHashSet("自住", "出租", "群租房");
            Set<String> a20ConditionSet = Sets.newHashSet("无人", "其他", "入户失败");
            String a17 = formSummary.getA17();
            String a20 = formSummary.getA20();
            if (!a17ConditionSet.contains(a17) || !a20ConditionSet.contains(a20)) {
                existedPlaceSet.add(placeKey);
                continue;
            }

            if (!existedPlaceSet.contains(placeKey)) {
                existedPlaceSet.add(placeKey);
                HouseSurveyFormPlaceVO vo = new HouseSurveyFormPlaceVO();
                BeanUtil.copyProperties(formSummary, vo);
                if (StringUtils.isNotBlank(vo.getA1())) {
                    vo.setA1Char(PinyinUtil.getFirstLetter(vo.getA1(), ""));
                } else {
                    vo.setA1Char("");
                }

                if (StringUtils.isBlank(formSummary.getA4())) noA4List.add(vo);
                else resultList.add(vo);
            }
        }

        resultList = sortForHouseSurveyByPlace(resultList, noA4List);
        return resultList;
    }

    @Override
    public List<HouseSurveyFormPlaceVO> listSecondHouseSurveyCenPeople(HouseSurveySecondCenQueryDTO queryDTO, String userId) {

        // 按照要求查找所有的户数
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(queryDTO.getSqfwId())) {
            cnd.and("sqfw_id", "=", queryDTO.getSqfwId());
        }
        cnd.and("unit_id", "=", queryDTO.getUnitId());
        cnd.and("type", "=", SqfwFormSummaryConstants.house_survey_form);
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> queryList = query(cnd);

        List<HouseSurveyFormPlaceVO> placeVOList = Lists.newArrayList();
        Set<String> existedPlaceSet = Sets.newHashSet();

        // 用来缓存a7转json的数据
        Map<String, List<Sqfw_cenSusPaper>> formSummaryCenPaperCacheMap = Maps.newHashMap();

        for (Sqfw_formSummary formSummary : queryList) {

            String placeKey = StrFormatter.format("{},{},{}", formSummary.getA1(), formSummary.getA4(), formSummary.getA5());

            String a7 = formSummary.getA7();
            if (StringUtils.isNotBlank(a7) && a7.equals("[]")) {
                existedPlaceSet.add(placeKey);
                continue;
            }
            if (!existedPlaceSet.contains(placeKey)) {

                if (StringUtils.isNotBlank(a7)) {
                    List<Sqfw_cenSusPaper> cenSusPaperList = JSONObject.parseArray(a7, Sqfw_cenSusPaper.class);

                    formSummaryCenPaperCacheMap.put(formSummary.getId(), cenSusPaperList);

                    if (cenSusPaperList.size() > 0) {
                        existedPlaceSet.add(placeKey);
                        HouseSurveyFormPlaceVO vo = new HouseSurveyFormPlaceVO();
                        BeanUtil.copyProperties(formSummary, vo);
                        if (StringUtils.isNotBlank(vo.getA1())) {
                            vo.setA1Char(PinyinUtil.getFirstLetter(vo.getA1(), ""));
                        } else {
                            vo.setA1Char("");
                        }
                        placeVOList.add(vo);
                    }
                }
            }
        }

        Set<String> specialMarkSet = Sets.newHashSet(queryDTO.getSpecialMarkList());

        Set<String> placeIdSet = Sets.newHashSet();
        for (HouseSurveyFormPlaceVO placeVO : placeVOList) {

            // 检查网格是否符合要求
            if (StringUtils.isNotBlank(queryDTO.getGrid())) {
                if (!placeVO.getA3().equals(queryDTO.getGrid())) {
                    continue;
                }
            }

            if (specialMarkSet.size() == 0) {
                placeIdSet.add(placeVO.getId());
                continue;
            }

            String a7 = placeVO.getA7();
            if (StringUtils.isNotBlank(a7)) {
                List<Sqfw_cenSusPaper> censusPaperList = formSummaryCenPaperCacheMap.get(placeVO.getId());
                for (Sqfw_cenSusPaper cenSusPaper : censusPaperList) {
                    if (StringUtils.isNotBlank(cenSusPaper.getSpecialMark())) {
                        // wzy 2023-11-24 specialMark变为以顿号隔开的数据
                        Set<String> cenSusPaperSet = Sets.newHashSet(Splitter.on("、").split(cenSusPaper.getSpecialMark()));
                        cenSusPaperSet.remove("");
                        // 求两个集合的交集，如果含有交集那么就认为满足条件

                        Collection<String> intersection = CollUtil.intersection(specialMarkSet, cenSusPaperSet);
                        if (intersection.size() > 0) {
                            placeIdSet.add(placeVO.getId());
                            break;
                        }
                    }
                }
            }
        }

        List<HouseSurveyFormPlaceVO> resultList = Lists.newArrayList();
        for (HouseSurveyFormPlaceVO placeVO : placeVOList) {
            if (placeIdSet.contains(placeVO.getId())) resultList.add(placeVO);
        }

        return resultList.stream().sorted(Comparator.comparing(HouseSurveyFormPlaceVO::getFillDate)).collect(Collectors.toList());
    }

    @Override
    public List<String> listGridByUnit(String unitId) {
        Cnd cnd = Cnd.NEW();
        cnd.and("unit_id", "=", unitId);
        cnd.asc("fill_date");
        cnd.and("type", "=", SqfwFormSummaryConstants.house_survey_form);
        List<Sqfw_formSummary> summaryList = query(cnd);

        Set<String> resultSet = Sets.newTreeSet();
        for (Sqfw_formSummary formSummary : summaryList) {
            String a3 = formSummary.getA3();
            if (StringUtils.isNotBlank(a3)) {
                try {
                    resultSet.add(a3);
                } catch (Exception ignored) {
                }
            }
        }
        return Lists.newArrayList((resultSet));
    }

    @Override
    public String generateServiceRecordPdfColl(List<ServiceRecordPdfOrExcelCollDTO> conditionList, Integer fileIndex) {

        // 威清门下载
        String userId = SecurityUtil.getUserId();
        Sys_user user = sysUserService.getUserById(userId);
        if (user.getUnitName().contains(StreetEnum.WEI_QING_MEN_STREET.getName()) && fileIndex != null) {
            List<String> sqwIds = conditionList.stream().map(ServiceRecordPdfOrExcelCollDTO::getSqfwId).collect(Collectors.toList());
            List<ExcelCreateConfig> excelConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(fileIndex.toString());
            excelConfigList.add(excelCreateConfig);
            List<ResultOfExcelGenerator> result = safetyCheckPdfService.downPdfList(excelConfigList, sqwIds);
            if (result.size() > 0) {
                return result.get(0).getExcelUrl();
            }
            return null;
        }

        // 目前pdf存储于两个地方，一个是安全排查、垃圾分类、入户调查等业务的pdf存储在工作流中的sqfw_complete_flow的resource中
        // 另外的 12345、八单一表、简报、日报、其他任务都是存储于fileReport这张表中。
        List<PdfResourceSortBO> pdfBoList = Lists.newArrayList();

        Set<String> flowTypeSet = Sets.newHashSet("垃圾分类", SupportBusinessTypeEnum.SAFETY_CHECK.getName(), "入户调查",
                SupportBusinessTypeEnum.MEET_RECORD.getName(), "社会治安", "社会治安重点场所巡查",
                SupportBusinessTypeEnum.SAFE_CHECK.getName(),
                SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName(), SqfwFormSummaryConstants.red_white_record);
        Set<String> fileReportTypeSet = Sets.newHashSet("12345", "简报", "八单一表", "日报", "其他");
        // 字典系统重构新需求功能(重构功能开发的)
        Map<String, ServiceRecordPdfOrExcelCollDTO> fromFlowDTOMap = Maps.newHashMap();
        Map<String, ServiceRecordPdfOrExcelCollDTO> fromFileReportMap = Maps.newHashMap();
        for (ServiceRecordPdfOrExcelCollDTO serviceRecordPdfOrExcelCollDTO : conditionList) {
            String serviceType = serviceRecordPdfOrExcelCollDTO.getServiceType();
            if (flowTypeSet.contains(serviceType))
                fromFlowDTOMap.put(serviceRecordPdfOrExcelCollDTO.getSqfwId(), serviceRecordPdfOrExcelCollDTO);
            if (fileReportTypeSet.contains(serviceType))
                fromFileReportMap.put(serviceRecordPdfOrExcelCollDTO.getSqfwId(), serviceRecordPdfOrExcelCollDTO);
        }

        // 首先查询存储于sqfw_complete_flow中的数据
        if (fromFlowDTOMap.size() > 0) {
            Cnd cnd = Cnd.NEW();
            cnd.and("sqfw_id", "in", fromFlowDTOMap.keySet());
            cnd.orderBy("fill_date", "asc");
            List<Sqfw_formSummary> formSummaryList = query(cnd);
            Map<String, Date> completeFlowIdDateMap = new HashMap<>();
            List<String> flowIdList = new ArrayList<>();
            if (formSummaryList.size() > 0) {
                completeFlowIdDateMap = formSummaryList.stream()
                        .collect(Collectors.toMap(Sqfw_formSummary::getSqfwFlowId, Sqfw_formSummary::getFillDate));
                flowIdList = formSummaryList.stream().map(Sqfw_formSummary::getSqfwFlowId).collect(Collectors.toList());
            } else {
                // 查询新表数据
                Cnd aNew = Cnd.NEW();
                SqlExpressionGroup where = aNew.where();
                where.andIn(Sqfw_formSummary_new::getSqfwId, fromFlowDTOMap.keySet().toArray(new String[0]));
                aNew.orderBy(Sqfw_formSummary_new::getFillDate, "asc");
                List<Sqfw_formSummary_new> formSummaryNews = sqfwFormsummaryNewService.query(aNew);
                completeFlowIdDateMap = formSummaryNews.stream()
                        .collect(Collectors.toMap(Sqfw_formSummary_new::getSqfwFlowId, Sqfw_formSummary_new::getFillDate));
                flowIdList = formSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());
            }

            Cnd flowCnd = Cnd.NEW();
            flowCnd.and("id", "in", flowIdList);
            List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.query(flowCnd);
            for (Sqfw_completeflow completeFlow : completeFlowList) {
                PdfResourceSortBO bo = new PdfResourceSortBO();
                Date fillDate = completeFlowIdDateMap.get(completeFlow.getId());
                bo.setSortDate(fillDate);
                bo.setSqfwId(completeFlow.getSqfwId());
                bo.setPdfPath(completeFlow.getResourcePath());
                bo.setServiceType(completeFlow.getFileType());
                pdfBoList.add(bo);
            }
        }

        // 然后从file_report中根据服务id查询出相关的数据 这一步我们使用循环查询的方式来操作
        if (fromFileReportMap.size() > 0) {
            Set<String> sqfwIdSet = fromFileReportMap.keySet();
            for (String sqfwId : sqfwIdSet) {

                Set<String> existedReportNameSet = Sets.newHashSet();

                Cnd fileReportCnd = Cnd.NEW();
                fileReportCnd.and("sqfw_id", "=", sqfwId).orderBy("create_date", "desc");
                List<Sqfw_reportFile> reportFileList = reportFileService.query(fileReportCnd);
                for (Sqfw_reportFile reportFile : reportFileList) {
                    String reportName = reportFile.getReportName();
                    if (StringUtils.isNotBlank(reportName) && !existedReportNameSet.contains(reportName)) {
                        existedReportNameSet.add(reportName);

                        PdfResourceSortBO bo = new PdfResourceSortBO();
                        bo.setSortDate(reportFile.getCreateDate());
                        bo.setSqfwId(reportFile.getSqfwId());
                        bo.setPdfPath(reportFile.getPdfFileUrl());
                        bo.setServiceType(reportFile.getServiceRecordType());
                        pdfBoList.add(bo);
                    }
                }
            }
        }

        // 将这些文档按照时间先后顺序进行排序
        pdfBoList.sort(Comparator.comparing(PdfResourceSortBO::getSortDate));

        List<String> pdfPathList = pdfBoList.stream().map(PdfResourceSortBO::getPdfPath).collect(Collectors.toList());

        // 用于生成文件规则
        Set<String> serviceTypeTotalSet = conditionList.stream().map(ServiceRecordPdfOrExcelCollDTO::getServiceType).collect(Collectors.toSet());
        String fileNameTemplate = "{}文档集合{}";

        String fileNamePrefix = "工作文档";
        if (serviceTypeTotalSet.size() == 1) fileNamePrefix = serviceTypeTotalSet.iterator().next();
        String fileName = StrFormatter.format(fileNameTemplate, fileNamePrefix, DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        return CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, fileName);
    }

    @Override
    public String generateServiceRecordExcelColl(List<ServiceRecordPdfOrExcelCollDTO> conditionList, String userId, Integer fileIndex, String excelType) {
        if (conditionList.size() == 0) return null;

        Set<String> serviceTypeSet = conditionList.stream().map(ServiceRecordPdfOrExcelCollDTO::getServiceType).collect(Collectors.toSet());
        if (serviceTypeSet.size() > 1) return "任务类型不同，无法合并";

        List<String> sqfwIdList = conditionList.stream().map(ServiceRecordPdfOrExcelCollDTO::getSqfwId).collect(Collectors.toList());

        Sys_user user = sysUserService.getUserById(userId);

        // 威清门合并
        if (user.getUnitName().contains(StreetEnum.WEI_QING_MEN_STREET.getName())) {
            List<ExcelCreateConfig> excelConfigList = new ArrayList<>();
            ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
            excelCreateConfig.setFileIdentity(fileIndex.toString());
            excelConfigList.add(excelCreateConfig);
            List<ResultOfExcelGenerator> result = safetyCheckExcelService.createExcel(excelConfigList, sqfwIdList);
            if (result.size() > 0) {
                return result.get(0).getExcelUrl();
            }
            return null;
        }

        String serviceType = conditionList.get(0).getServiceType();

        String fileNameSuffix = StrFormatter.format("集合{}", DateUtil.format(new Date(), "yyyyMMddHHmmss"));

        if (serviceType.equals("安全排查")) {
            return generateFireHiddenCollectionExcelForApp(sqfwIdList, null, userId, fileIndex, fileNameSuffix, null, null);
        }

        if (serviceType.equals("垃圾分类")) {
            return generateRefuseClassifyExcelForApp(sqfwIdList, fileNameSuffix);
        }

        if (serviceType.equals("入户调查")) {
            return generateHouseSurveyFormExcelForApp(sqfwIdList, excelType, fileNameSuffix);
        }

        // 会议记录
        if (SupportBusinessTypeEnum.MEET_RECORD.getName().equals(serviceType)) {
            return meetingMinutesService.mergeExcelLedgerBySqfwIds(sqfwIdList, fileNameSuffix);
        }

        if (SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName().equals(serviceType)) {
            return oldCareServiceStationExcelService.generateExcelColForApp(sqfwIdList);
        }

        // 红白事
        if (SqfwFormSummaryConstants.red_white_record.equals(serviceType)) {
            if (user.getUnitName().contains(DA_YING_LU_STREET.getName())) {
                List<ExcelCreateConfig> excelConfigList = new ArrayList<>();
                ExcelCreateConfig createConfig = new ExcelCreateConfig();
                createConfig.setFileIdentity(fileIndex.toString());
                excelConfigList.add(createConfig);
                List<GenerateExcelUrlVO> vos = daYingLuRedWhiteRecordExcelService.createExcel(excelConfigList,
                        userId, sqfwIdList, null, null);
                return vos.get(0).getExcelUrl();
            }
        }

        return null;
    }

    private List<HouseSurveyFormPlaceVO> sortForHouseSurveyByPlace(List<HouseSurveyFormPlaceVO> tempResultList, List<HouseSurveyFormPlaceVO> noA4List) {

        List<HouseSurveyFormPlaceVO> resultList = Lists.newArrayList();

        tempResultList = tempResultList.stream().sorted(
                Comparator.comparing(HouseSurveyFormPlaceVO::getA1Char)
                        .thenComparing(HouseSurveyFormPlaceVO::getA4)
                        .thenComparing(HouseSurveyFormPlaceVO::getA5)
        ).collect(Collectors.toList());

        noA4List = noA4List.stream().sorted(
                Comparator.comparing(HouseSurveyFormPlaceVO::getA1Char)
                        .thenComparing(HouseSurveyFormPlaceVO::getA5)
        ).collect(Collectors.toList());


        resultList.addAll(tempResultList);
        resultList.addAll(noA4List);
        return resultList;
    }

    /**
     * 根据表单数据和工作流船舰垃圾分类的pdf
     *
     * @param userId       用户id
     * @param completeFlow 工作流
     * @param formSummary  表单数据
     */
    private void generateRefuseClassifyPDFByFlowAndForm(String userId, Sqfw_completeflow completeFlow, Sqfw_formSummary formSummary) {

        System.out.println("开始创建垃圾分类排查表PDF");

        // 生成word和pdf
        String unitId = formSummary.getUnitId();
        Sys_unit unit = sysUnitService.fetch(unitId);

        FireHiddenCheckWordDTO wordDTO = new FireHiddenCheckWordDTO();
        BeanUtil.copyProperties(formSummary, wordDTO);
        wordDTO.setCompleteUnitName(unit.getName());

        String createUserSignature = getCreateUserSignature(completeFlow.getUserId());
        wordDTO.setRefuseClassifyCreateUserSigUrl(createUserSignature);

        try {
            GenerateWordAndPdfUrlVO wordVO = new GenerateWordAndPdfUrlVO();
            if (formSummary.getCommunity().contains("云潭街道")) {
                // 如果为宇虹社区 则使用宇虹社区的
                wordVO = RefuseClassifyOfficeUtils.createWordAndPdfUrlCheckFormYuHongSQ(wordDTO);
            } else {
                wordVO = RefuseClassifyOfficeUtils.createWordAndPdfUrlCheckForm(wordDTO);
            }
            if (StringUtils.isBlank(wordVO.getPdfUrl())) {
                completeFlow.setResourcePath("error");
            } else {
                completeFlow.setResourcePath(wordVO.getPdfUrl());
                sqfwCompleteflowService.update(completeFlow);

                // 发送一个websocket通知前端
                WebSocketMsgDTO msgDTO = new WebSocketMsgDTO();
                msgDTO.setType(SqfwWebSocketMsgConstants.work_flow_refuse_classify_pdf_created);
                msgDTO.setMsg("垃圾分类表PDF生成成功");
                sqfwWebSocket.sendMessage(userId, msgDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("创建消防排查PDF失败");
            completeFlow.setResourcePath("error");
            sqfwCompleteflowService.update(completeFlow);
        }
    }

    private void generateHouseSurveyFormPDFByFlowAndForm(String userId, Sqfw_completeflow completeFlow, Sqfw_formSummary formSummary) {

        log.info("start generateHouseSurveyFormPDFByFlowAndForm info userId: {}, param: {}", userId, JSONObject.toJSONString(formSummary));
        // 生成word和pdf
        String unitId = formSummary.getUnitId();
        Sys_unit unit = sysUnitService.fetch(unitId);

        HouseSurveyWordDTO wordDTO = new HouseSurveyWordDTO();
        BeanUtil.copyProperties(formSummary, wordDTO);
        wordDTO.setCompleteUnitName(unit.getName());
        wordDTO.setCreateUserSigUrl(getCreateUserSignature(formSummary.getCreateBy()));

        try {
            GenerateWordAndPdfUrlVO wordVO = HouseSurveyFormOfficeUtils.createWordAndPdfUrlCheckForm(wordDTO);
            if (StringUtils.isBlank(wordVO.getPdfUrl())) {
                completeFlow.setResourcePath("error");
            } else {
                completeFlow.setResourcePath(wordVO.getPdfUrl());
                sqfwCompleteflowService.update(completeFlow);

                // 发送一个websocket通知前端
                WebSocketMsgDTO msgDTO = new WebSocketMsgDTO();
                msgDTO.setType(SqfwWebSocketMsgConstants.work_flow_house_survey_form_pdf_created);
                msgDTO.setMsg("入户调查表PDF生成成功");
                sqfwWebSocket.sendMessage(userId, msgDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("创建入户调查表PDF失败");
            completeFlow.setResourcePath("error");
            sqfwCompleteflowService.update(completeFlow);
        }
    }

    /**
     * 在生成文档之前插入工作流和表单的数据
     *
     * @param userId              用户id
     * @param formSummaryWithFlow 工作流
     * @param formSummaryType     表单数据
     */
    private void insertWordFlowAndFormSummary(String userId, SqfwFormSummaryWithFlowDTO formSummaryWithFlow, String formSummaryType) {
        Trans.exec(() -> {
            Sys_user sysUser = sysUserService.fetch(userId);

            // 首先现需要生成一个工作流信息
            SqfwCompleteFlowUpdateDTO completeFlow = formSummaryWithFlow.getCompleteFlow();
            completeFlow.setResourcePath("creating");
            sqfwCompleteflowService.insertCompleteflow(completeFlow, sysUser);

            // 更新工单表中的最新工作流备注
            sqfwWorkorderService.updateLatestFlowRemarkWithCompleteFlow(completeFlow.getWorkerId(), completeFlow.getFileType(), false);

            // 然后生成一个表单数据
            Sqfw_formSummary formSummary = formSummaryWithFlow.getFormSummary();
            formSummary.setCreateDate(new Date());
            formSummary.setCreateBy(userId);
            formSummary.setSqfwId(completeFlow.getSqfwId());
            formSummary.setWorkOrderId(completeFlow.getWorkerId());
            formSummary.setSqfwFlowId(completeFlow.getId());
            formSummary.setCreateUserName(sysUser.getUsername());
            formSummary.setCreateUserPhone(sysUser.getLoginname());
            formSummary.setType(formSummaryType);
            // wzy 2023-11-13 由后端赋值这一张表的四级数据
            formSummary.setProvince(sysUser.getProvince());
            formSummary.setCity(sysUser.getCity());
            formSummary.setCounty(sysUser.getCounty());
            formSummary.setDistrict(sysUser.getDistrict());
            formSummary.setCommunity(sysUser.getCommunity());
            formSummary.setCheckStatus(SqfwFormSummaryFieldEnum.check_status_init.getCode());

            // 如果是市南社区的话，如果只传了整改后照片，那么需要查询出之前最近的一次的整改前照片进行赋值
            String unitName = formSummary.getUnitName();
            if (unitName.contains("油榨街")) {
                if (formSummaryType.equals(SqfwFormSummaryConstants.safety_check)) {
                    // 如果整改前照片为空 并且 整改后照片不为空 那么就进行操作
                    if (StringUtils.isBlank(formSummary.getA11()) && StringUtils.isNotBlank(formSummary.getA12())) {
                        // 根据 场所名称 和 类型进行取值
                        Cnd cnd = Cnd.NEW();
                        cnd.and("a1", "=", formSummary.getA1())
                                .and("type", "=", SqfwFormSummaryConstants.safety_check)
                                .and("a41", "is not ", null)
                                .and("a41", "!=", "");
                        cnd.orderBy("fill_date", "desc");
                        Sqfw_formSummary queryFormSummary = fetch(cnd);
                        if (queryFormSummary != null) formSummary.setA11(queryFormSummary.getA11());
                    }
                }
            }

            if (unitName.contains("金元") || unitName.contains("润兴")) {
                if (formSummaryType.equals(SqfwFormSummaryConstants.safety_check)) {
                    if (StringUtils.isNotBlank(formSummary.getA45()) && formSummary.getA45().equals("已整改")
                            && StringUtils.isNotBlank(formSummary.getA11())
                            && StringUtils.isBlank(formSummary.getA10())) {
                        // 根据 场所名称 和 类型进行取值
                        Cnd cnd = Cnd.NEW();
                        cnd.and("a1", "=", formSummary.getA1())
                                .and("type", "=", SqfwFormSummaryConstants.safety_check)
                                .and("a45", "=", "未整改");
                        cnd.orderBy("fill_date", "desc");
                        Sqfw_formSummary queryFormSummary = fetch(cnd);
                        if (queryFormSummary != null) formSummary.setA10(queryFormSummary.getA10());
                    }
                }
            }

            if (unitName.contains("大营路")) {
                if (formSummaryType.equals(SqfwFormSummaryConstants.safety_check)) {
                    // 根据 场所名称、类型、unitId ，填表时间逆序排序来获取上一次填表数据
                    Cnd cnd = Cnd.NEW();
                    cnd.and("a1", "=", formSummary.getA1())
                            .and("type", "=", SqfwFormSummaryConstants.safety_check)
                            .and("unit_id", "=", formSummary.getUnitId());
                    cnd.orderBy("fill_date", "desc");
                    Sqfw_formSummary lastCheckSummary = fetch(cnd);
                    popularDaYingLuStreetLastCheckSummary(lastCheckSummary, formSummary);
                    updateIgnoreNull(lastCheckSummary);

                    // wzy 2023-11-2 如果当前只提交了一张整改后的照片，那么就需要把上一次提交的违规住人的照片赋值下来
                    if (StringUtils.isBlank(formSummary.getA39()) && StringUtils.isNotBlank(formSummary.getA40())) {
                        //zhangp 2024-01-04 根据条件查询如果上一次检查是空lastCheckSummary，则不赋值，增加判断否则报空指针
                        if (null != lastCheckSummary && StringUtils.isNotBlank(lastCheckSummary.getA39())) {
                            formSummary.setA39(lastCheckSummary.getA39());
                        }
                    }
                }

            }

            if (formSummaryType.equals(SqfwFormSummaryConstants.public_security)) {
                // 根据 场所名称、场所地址、类型、unitId ，填表时间逆序排序来获取上一次填表数据
                Cnd cnd = Cnd.NEW();
                cnd.and("a1", "=", formSummary.getA1())
                        .and("a3", "=", formSummary.getA3())
                        .and("type", "=", SqfwFormSummaryConstants.public_security)
                        .and("unit_id", "=", formSummary.getUnitId());
                cnd.orderBy("fill_date", "desc");
                Sqfw_formSummary lastCheckSummary = fetch(cnd);
                if (null != lastCheckSummary) {
                    lastCheckSummary.setCheckStatus("2");
                    updateIgnoreNull(lastCheckSummary);
                }
            }

            // 威清门设置巡查状态
            if (unitName.contains(StreetEnum.WEI_QING_MEN_STREET.getName())) {
                //获取上一次的巡查
                Cnd cnd = Cnd.NEW();
                cnd.and("unit_id", "=", formSummary.getUnitId())
                        .and("a1", "=", formSummary.getA1())
                        .and("sqfw_id", "=", formSummary.getSqfwId())
                        .and("fill_date", "<", formSummary.getFillDate());
                cnd.orderBy("fill_date", "desc");
                Sqfw_formSummary formSummaryUp = this.fetch(cnd);
                if (formSummaryUp != null) {
                    String a7_up = formSummaryUp.getA7();
                    String a42_up = formSummaryUp.getA42();
                    String a7 = formSummary.getA7();
                    String a41 = formSummary.getA41();
                    String a42 = formSummary.getA42();
                    if ("有".equals(a7_up) && "无".equals(a7)) {
                        formSummary.setA64("已整改");
                    } else if ("有".equals(a7)) {
                        formSummary.setA64("未整改");
                    } else {
                        formSummary.setA64("正常");
                    }
                    if (getSize(a42) > 0 || "未整改".equals(formSummary.getA64())) {
                        formSummary.setA37("未整改");
                    } else if (getSize(a41) > 0 || (getSize(a42_up) > 0 && getSize(a41) == 0) || "已整改".equals(formSummary.getA64())) {
                        formSummary.setA37("已整改");
                    } else {
                        formSummary.setA37("正常");
                    }
                } else {
                    String a7 = formSummary.getA7();
                    String a41 = formSummary.getA41();
                    String a42 = formSummary.getA42();

                    if ("有".equals(a7)) {
                        formSummary.setA64("未整改");
                    } else {
                        formSummary.setA64("正常");
                    }

                    if (getSize(a42) > 0 || "未整改".equals(formSummary.getA64())) {
                        formSummary.setA37("未整改");
                    } else if (getSize(a41) > 0 || "已整改".equals(formSummary.getA64())) {
                        formSummary.setA37("已整改");
                    } else {
                        formSummary.setA37("正常");
                    }
                }
            }

            // 如果是入户调查
            if (formSummaryType.equals(SqfwFormSummaryConstants.house_survey_form)) {
                fromSummaryComponent.addCenSusPaperByHouseSurveyForm(formSummary);
            }

            // wzy 2023-11-22 需要查询上一次的数据来对字段check_status进行赋值
            if (formSummaryType.equals(SqfwFormSummaryConstants.safety_check)) {
                updateLastFormSummaryData(formSummary);
            }

            log.info("insert formSummary request param: {}", JSONObject.toJSONString(formSummary));
            insert(formSummary);
            // 更新住户表信息
            if (formSummaryType.equals(SqfwFormSummaryConstants.house_survey_form)) {
                String a7 = formSummary.getA7();
                if (StringUtils.isNotBlank(a7)) {
                    List<Sqfw_cenSusPaper> papers = JSONArray.parseArray(a7, Sqfw_cenSusPaper.class);
                    papers.forEach(p -> p.setSqfwSummaryId(formSummary.getId()));
                    sqfwCenSusPaperService.updateIgnoreNull(papers);
                }
            }
        });
    }

    private int getSize(String str) {
        if (StringUtils.isBlank(str)) return 0;
        if (str.contains("[")) {
            JSONArray jsonArray = JSON.parseArray(str);
            return jsonArray.getJSONArray(0).size() + jsonArray.getJSONArray(1).size() + jsonArray.getJSONArray(2).size();
        }
        return 0;
    }

    /**
     * 更新上一次检查的检查状态
     *
     * @param formSummary
     */
    private void updateLastFormSummaryData(Sqfw_formSummary formSummary) {

        String countyStr = formSummary.getCounty();
        if (StringUtils.isBlank(countyStr)) countyStr = formSummary.getUnitName();
        if (StringUtils.isBlank(countyStr)) return;

        Cnd lastForSummaryCnd = Cnd.NEW();

        // 进行条件判断
        if (countyStr.contains("威清门")) {
            lastForSummaryCnd.and(Sqfw_formSummary::getA1, "=", formSummary.getA1());
            lastForSummaryCnd.and(Sqfw_formSummary::getA2, "=", formSummary.getA2());
        } else if (countyStr.contains("云潭街道")) {
            lastForSummaryCnd.and(Sqfw_formSummary::getA1, "=", formSummary.getA1());
            lastForSummaryCnd.and(Sqfw_formSummary::getA2, "=", formSummary.getA2());
        } else {
            lastForSummaryCnd.and(Sqfw_formSummary::getA1, "=", formSummary.getA1());
            lastForSummaryCnd.and(Sqfw_formSummary::getA3, "=", formSummary.getA3());
        }

        lastForSummaryCnd.and(Sqfw_formSummary::getType, "=", SqfwFormSummaryConstants.safety_check);

        lastForSummaryCnd.and(Sqfw_formSummary::getUnitId, "=", formSummary.getUnitId());
        if (StringUtils.isNotBlank(formSummary.getId())) {
            lastForSummaryCnd.and(Sqfw_formSummary::getId, "!=", formSummary.getId());
        }
        lastForSummaryCnd.and(Sqfw_formSummary::getFillDate, "<", new Date());
        // 排除直接导入商铺的时间：2023-01-01 00:00:00
        lastForSummaryCnd.and("to_char(fill_date, 'YYYY-MM-DD HH24:MI:SS')", "!=", "2023-01-01 00:00:00");
        lastForSummaryCnd.desc(Sqfw_formSummary::getFillDate);
        List<Sqfw_formSummary> lastFormSummaryList = query(lastForSummaryCnd);
        if (lastFormSummaryList.size() > 0) {
            for (Sqfw_formSummary lastFormSummary : lastFormSummaryList) {
                lastFormSummary.setCheckStatus(SqfwFormSummaryFieldEnum.check_status_checked.getCode());
                updateIgnoreNull(lastFormSummary);
            }
        }
    }


    /**
     * 根据社区的名称创建消防安全排查表
     *
     * @param wordDTO 消防安全工单
     * @return 结果
     */
    private GenerateWordAndPdfUrlVO createFireHiddenCheckFormWordAndPDFByUnitName(FireHiddenCheckWordDTO wordDTO) {
        String unitName = wordDTO.getUnitName();

        Sys_user sysUser = sysUserService.getUserById(wordDTO.getCreateBy());
        wordDTO.setCreateUserName(sysUser.getUsername());

        wordDTO.setProvince(sysUser.getProvince());
        wordDTO.setCity(sysUser.getCity());
        wordDTO.setDistrict(sysUser.getDistrict());
        wordDTO.setCounty(sysUser.getCounty());
        wordDTO.setCommunity(sysUser.getCommunity());
        wordDTO.setUnitName(sysUser.getUnitName());

        GenerateWordAndPdfUrlVO resultVO;

        /**
         * ywm
         */
        GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = FireHiddenOfficeFactory.createOffice(wordDTO);
        if (generateWordAndPdfUrlVO != null) {
            return generateWordAndPdfUrlVO;
        }

        if (unitName.contains("油榨街")) {
            String a18 = wordDTO.getA18();
            Map<String, List<String>> userSignatureMap = getUserSignatureMap(a18, wordDTO.getUnitId());
            wordDTO.setA18NoSignatureUsers(userSignatureMap.get("noSig"));
            wordDTO.setA18UserSignatureUrls(userSignatureMap.get("sig"));

            resultVO = FireHiddenOfficeUtils.createFireHiddenYouZhaJieShiNanSQ(wordDTO);
        } else if (unitName.contains("金元") || unitName.contains("润兴") || unitName.contains("金阳")) {
            // a18 排查人员
            String a18 = wordDTO.getA18();
            Map<String, List<String>> userSignatureMap = getUserSignatureMap(a18, wordDTO.getUnitId());

            JinYangStreetFireHiddenCheckWordDTO jinYangWordDTO = new JinYangStreetFireHiddenCheckWordDTO();
            BeanUtil.copyProperties(wordDTO, jinYangWordDTO);

            // 含有签名图片的和没有签名图片的
            jinYangWordDTO.setJinYuanA18NoSigUsers(userSignatureMap.get("noSig"));
            jinYangWordDTO.setJinYuanA18SigUrls(userSignatureMap.get("sig"));
            jinYangWordDTO.setCompleteUnitName(unitName);
            jinYangWordDTO.setUnitName(unitName);

            String createUserSigUrl = getCreateUserSignature(wordDTO.getCreateBy());
            jinYangWordDTO.setJinYuanFireHiddenCreateUserSig(createUserSigUrl);

            // 两个社区文档的标题有些许差别
            if (unitName.contains("金元")) {
                jinYangWordDTO.setVisAndInsDocTitlePrefix(StrFormatter.format("金阳街道金元社区九小场所{}", DateUtil.format(jinYangWordDTO.getFillDate(), "yyyy年MM月dd日")));
                jinYangWordDTO.setStandingBookDocTitlePrefix("金阳街道金元社区");
                jinYangWordDTO.setGasInsDocTitlePrefix("金阳街道金元社区");
                jinYangWordDTO.setGasRecDocTitlePrefix("观山湖区金阳街道（金元社区）");
            }

            if (unitName.contains("润兴")) {
                jinYangWordDTO.setVisAndInsDocTitlePrefix(StrFormatter.format("金阳街道润兴居委会{}", DateUtil.format(jinYangWordDTO.getFillDate(), "yyyy年MM月dd日")));
                jinYangWordDTO.setStandingBookDocTitlePrefix("金阳街道润兴居委会");
                jinYangWordDTO.setGasInsDocTitlePrefix("金阳街道润兴居委会");
                jinYangWordDTO.setGasRecDocTitlePrefix("观山湖区金阳街道（润兴居委会）");
            }

            resultVO = FireHiddenOfficeUtils.createFireHiddenJinYuanSQ(jinYangWordDTO);
        } else if (unitName.contains("大营路") ||
                (StringUtils.isNotBlank(wordDTO.getArea()) && wordDTO.getArea().contains("大营路"))) {
            DaYingLuStreetFireHiddenCheckWordDTO daYingLuWordDTO = new DaYingLuStreetFireHiddenCheckWordDTO();
            BeanUtil.copyProperties(wordDTO, daYingLuWordDTO);

            String a18 = wordDTO.getA18();
            Map<String, List<String>> userSignatureMap = getUserSignatureMap(a18, wordDTO.getUnitId());

            // 含有签名图片的和没有签名图片的
            daYingLuWordDTO.setA18NoSignatureUsers(userSignatureMap.get("noSig"));
            daYingLuWordDTO.setA18UserSignatureUrls(userSignatureMap.get("sig"));

            // 根据a1和unitId查询上一次检查的结果
            DaYingLuStreetFireHiddenCheckWordDTO lastCheckWordDTO = getLastCheckWordDTOForDaYingLuFireHidden(
                    daYingLuWordDTO.getUnitId(), daYingLuWordDTO.getA1(), daYingLuWordDTO.getType(), daYingLuWordDTO.getFillDate());
            daYingLuWordDTO.setLastCheckFormSummary(lastCheckWordDTO);

            resultVO = DaYingLuStreetFireHiddenOfficeUtils.createFireHiddenPDF(daYingLuWordDTO);

        } else {
            // 花果园 生成消防安全排查pdf
            String a18 = wordDTO.getA18();
            Map<String, List<String>> userSignatureMap = getUserSignatureMap(a18, wordDTO.getUnitId());
            wordDTO.setA18NoSignatureUsers(userSignatureMap.get("noSig"));
            wordDTO.setA18UserSignatureUrls(userSignatureMap.get("sig"));
            resultVO = FireHiddenOfficeUtils.createFireHiddenHuaGuoYuan(wordDTO);
        }

        return resultVO;
    }

    /**
     * 获取上一次检查
     *
     * @param address 场所地址
     * @param name    场所名称
     * @return
     */
    public Sqfw_formSummary getLastCheck(String address, String name) {
        Cnd cnd = Cnd.NEW();
        cnd.and("a2", "=", address)
                .and("a1", "=", name);
        cnd.orderBy("fill_date", "desc");
        Sqfw_formSummary formSummary = this.fetch(cnd);
        return formSummary;
    }

    @Override
    public Sqfw_formSummary getToSqfwId(String sqfw_id, String createDate) {
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "=", sqfw_id);
        cnd.and("to_char(create_date, 'YYYY-MM-DD HH24:MI:SS')", "=", createDate);
        cnd.orderBy("create_date", "desc");
        Sqfw_formSummary formSummary = this.fetch(cnd);
        return formSummary;
    }


    /**
     * 当生成pdf和excel之后需要发送短信通知
     *
     * @param userId          用户id
     * @param phone           用户电话
     * @param messageSendFlag 成功标志
     */
    private void sendMsgAfterFireHiddenPdfOrExcel(String userId, String phone, boolean messageSendFlag, Sqfw_Sms_Msg smsMsg) {
        // 发送一个websocket通知前端
        WebSocketMsgDTO msgDTO = new WebSocketMsgDTO();
        msgDTO.setType(SqfwWebSocketMsgConstants.work_flow_fire_hazards_pdf_created);
        msgDTO.setMsg("消防安全Excel生成成功");
        sqfwWebSocket.sendMessage(userId, msgDTO);

        if (messageSendFlag) {
            // 发送短信通知被检查人手机
            SmsMsgDTO smsMsgDTO = new SmsMsgDTO();
            smsMsgDTO.setPhoneNumberSet(Sets.newHashSet(phone));

            String url = DfxyWeChatMPUtils.generatedDfxyMiniProgramUrl("/pages/user-center/safeList");
            if (StringUtils.isNotBlank(url)) {
                Integer status = ztSmsService.ztSendSafetyCheckInfoMsg(phone, url);
                if (smsMsg != null) {
                    smsMsg.setStatus(status == 1 ? "成功" : "失败");
                    smsMsg.setMsg("");
                    smsMsg.setCreateDate(new Date());
                    sqfwSmsMsgService.insert(smsMsg);
                }
            }
        }
    }

    public Map<String, List<String>> getUserSignatureMap(String nameStr, String unitId) {
        List<String> picUrlList = Lists.newArrayList();
        List<String> noPicUserNameList = Lists.newArrayList();

        String[] userNameArray = nameStr.split(",");
        List<Sys_user> checkUserList = sysUserService.query(Cnd.NEW().and("username", "in", Sets.newHashSet(userNameArray)).and("unitid", "=", unitId));
        for (Sys_user checkUser : checkUserList) {
            String signatureUrl = checkUser.getSignatureUrl();
            if (StringUtils.isNotBlank(signatureUrl)) {
                if (signatureUrl.startsWith("/"))
                    signatureUrl = NutzIocUtils.getOssPrefix() + signatureUrl;
                picUrlList.add(signatureUrl);
            } else {
                noPicUserNameList.add(checkUser.getUsername());
            }
        }

        Map<String, List<String>> resultMap = Maps.newHashMap();
        resultMap.put("sig", picUrlList);
        resultMap.put("noSig", noPicUserNameList);

        return resultMap;
    }

    @Override
    public List<Map> getServiceRecordFormSummaryList(String userName, String specialMark) {
        if (StringUtils.isBlank(userName) || StringUtils.isBlank(specialMark)) {
            throw new ServiceException("人员名称、人员标识都不能为空！");
        }
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        String sqlStr = " select a.id,a.sqfw_summary_id,a.detail_address,case when c.name is null  then a.name else concat(a.name,'、',c.name) end as name ,b.a18,b.fill_date from " +
                " ( select * from shequ.sqfw_censuspaper sc where  " +
                " sc.name ='" + userName +
                "' and sc.special_mark ='" + specialMark +
                "' ) a left join " +
                " (select * from shequ.sqfw_form_summary sfs where sfs.type='入户调查' )b on b.id=a.sqfw_summary_id " +
                " left join shequ.sqfw_censuspaper c on c.sqfw_summary_id =a.sqfw_summary_id  and c.id  != a.id " +
                " where   b.a7 is not null " +
                "  and a.province = '" + user.getProvince() +
                "' and a.city = '" + user.getCity() +
                "' and a.district = '" + user.getDistrict() +
                "' and a.county = '" + user.getCounty() +
                "' and a.community = '" + user.getCommunity() +
                "' order by b.create_date desc";
        Sql sql = Sqls.create(sqlStr);
        sql.setCallback((Connection con, ResultSet rs, Sql sqlItem) -> {
            List<Map<String, Object>> list = Lists.newArrayList();
            while (rs.next()) {
                Map<String, Object> map = new HashMap<>();
                map.put("sqfwSummaryId", rs.getString("sqfw_summary_id"));
                map.put("name", rs.getString("name"));
                map.put("detailAddress", rs.getString("detail_address"));
                map.put("type", rs.getString("a18"));
                map.put("date", rs.getString("fill_date"));
                list.add(map);
            }
            return list;
        });
        dao().execute(sql);
        return sql.getList(Map.class);
    }


    @Override
    public List<Sqfw_formSummary> getStoreInfo(String status, Integer pageNo, Integer pageSize, String content) {
        Sys_user sysUser = sysUserService.getUserById(SecurityUtil.getUserId());
        StringBuilder sqlStr = new StringBuilder();
        if (sysUser.getDistrict().contains("观山湖")) {
            //世纪城
            buildCenturyCitySqlParam(sqlStr, sysUser, status);
        } else {
            sqlStr.append(" select a.* from (");
            sqlStr.append(" select *,");
            sqlStr.append(" case  when floor(now() - fill_date) >=30 then 1 else 0 end as timeout_status,");
            sqlStr.append(" row_number() over(partition by a1 order by fill_date desc) as num  ");
            sqlStr.append(" from shequ.sqfw_form_summary sfs ");
            sqlStr.append(" where sfs.type ='安全排查' ");
            sqlStr.append(" and province ='").append(sysUser.getProvince()).append("'");
            sqlStr.append(" and city ='").append(sysUser.getCity()).append("'");
            sqlStr.append(" and district ='").append(sysUser.getDistrict()).append("'");
            sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
            sqlStr.append(" and community ='").append(sysUser.getCommunity()).append("'");
            sqlStr.append(" ) a where a.num=1 ");
        }
        //超时状态status，0-全部,1-已超时，2-未超时
        if (SqfwFormSummaryFieldEnum.check_status_checked.getCode().equals(status)) {
            //sqlStr.append(" and a.check_status ='").append(status).append("'");
            sqlStr.append(" and a.timeout_status ='0' and  a.check_status <> 3");
        }
        if (SqfwFormSummaryFieldEnum.check_status_init.getCode().equals(status)) {
            /* sqlStr.append(" and a.check_status ='").append(status).append("'");*/
            sqlStr.append(" and a.timeout_status ='1' and  a.check_status <> 3");
        }
        if (SqfwFormSummaryFieldEnum.CHECK_STATUS_CLOSED.getCode().equals(status)) {
            /* sqlStr.append(" and a.check_status ='").append(status).append("'");*/
            sqlStr.append(" and a.check_status = 3");
        }
        if (StringUtils.isNotBlank(content)) {
            sqlStr.append(" and (a.a1 like '%").append(content).append("%' or a.a3 like '%").append(content).append("%') ");
        }
        sqlStr.append(" order by a.check_status asc, a.fill_date desc, a.id desc");
        if (null != pageNo) {
            if (null == pageSize) {
                pageSize = 10;
            }
            if (pageNo >= 1) {
                pageNo = (pageNo - 1) * pageSize;
            }
            if (0 != pageSize) {
                sqlStr.append(" LIMIT ").append(pageSize).append(" OFFSET ").append(pageNo);
            }
        }

        List<NutMap> nutMapList = listMap(Sqls.create(sqlStr.toString()));
        return JSONUtil.toList(JSONUtil.toJsonStr(nutMapList), Sqfw_formSummary.class);
    }

    private void buildCenturyCitySqlParam(StringBuilder sqlStr, Sys_user sysUser, String status) {
        sqlStr.append(" select * from (");
        sqlStr.append(" select ");
        sqlStr.append(" id,");
        sqlStr.append(" place_name as a1,");
        sqlStr.append(" operator as a2,");
        sqlStr.append(" address as a3,");
        sqlStr.append(" operator_telephone as a8, ");
        sqlStr.append(" update_date as fill_date,");
        sqlStr.append(" CASE WHEN (shop_status !='3' or shop_status is null) THEN 1 ELSE 3 END as check_status , ");
        sqlStr.append(" case  when floor(now() - update_date) >=30 then 1 else 0 end as timeout_status");
        sqlStr.append(" from shequ.sqfw_shops_base_info ssbi where 1=1");
        sqlStr.append(" and province ='").append(sysUser.getProvince()).append("'");
        sqlStr.append(" and city ='").append(sysUser.getCity()).append("'");
        sqlStr.append(" and district ='").append(sysUser.getDistrict()).append("'");
        sqlStr.append(" and service_type like '%").append(SupportBusinessTypeEnum.SAFETY_CHECK.getCode()).append("%'");
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCounty())) {
            sqlStr.append(" and county ='").append(sysUser.getCounty()).append("'");
        }
        if (!CommonConstants.DIRECTLY_UNDER.equals(sysUser.getCommunity())) {
            sqlStr.append(" and community ='").append(sysUser.getCommunity()).append("'");
        }
        sqlStr.append(" ) a where 1=1  ");
    }


    /**
     * 获取系统用户的签名图片
     *
     * @param createBy 系统用户id
     * @return 结果
     */
    private String getCreateUserSignature(String createBy) {
        Sys_user sysUser = sysUserService.fetch(createBy);
        if (sysUser == null) return null;
        return sysUser.getSignatureUrl();
    }

    /**
     * 大营路街道消防安全根据a1,type=安全排查和unitId来查询上一次填表的数据
     *
     * @return 结果
     */
    private DaYingLuStreetFireHiddenCheckWordDTO getLastCheckWordDTOForDaYingLuFireHidden(String unitId, String a1, String type, Date fillDate) {
        Cnd cnd = Cnd.NEW();
        cnd.and("unit_id", "=", unitId).and("a1", "=", a1).and("type", "=", type).and("fill_date", "<", fillDate);
        cnd.orderBy("fill_date", "desc");
        Sqfw_formSummary lastCheckFormSummary = fetch(cnd);
        if (lastCheckFormSummary == null) return null;

        // wzy 2023-10-11 如果上一次a61第四组没有问题的话就不处理
        String a61 = lastCheckFormSummary.getA61();
        if (StringUtils.isBlank(a61)) return null;
        List<String> a61List = JSONObject.parseArray(a61, String.class);
        Set<String> a61_4Set = Sets.newHashSet(JSONObject.parseArray(a61List.get(5), String.class));
        a61_4Set.remove("");
        if (a61_4Set.size() == 0) return null;

        DaYingLuStreetFireHiddenCheckWordDTO daYingLuWordDTO = new DaYingLuStreetFireHiddenCheckWordDTO();
        BeanUtil.copyProperties(lastCheckFormSummary, daYingLuWordDTO);

        String a18 = lastCheckFormSummary.getA18();
        Map<String, List<String>> userSignatureMap = getUserSignatureMap(a18, lastCheckFormSummary.getUnitId());

        // 含有签名图片的和没有签名图片的
        daYingLuWordDTO.setA18NoSignatureUsers(userSignatureMap.get("noSig"));
        daYingLuWordDTO.setA18UserSignatureUrls(userSignatureMap.get("sig"));

        return daYingLuWordDTO;
    }

    /**
     * 判断上一次整改是否已经整改完成
     *
     * @param lastCheckSummary 上一次检查情况
     * @param formSummary      本次检查情况
     */
    public void popularDaYingLuStreetLastCheckSummary(Sqfw_formSummary lastCheckSummary, Sqfw_formSummary formSummary) {

        // 现在这段代码想要实现的效果就是
        // 根据这一次提交的问题比较上一次提交的问题，然后更新上一次a27这个字段(a27字段：问题是否已经整改)

        // 注意几个细节
        // 如果该次提交的数据全是现场整改，没有限期整改的内容，如果上一次有问题那么上一次的a27就是已整改
        // 如果该次提交的数据有限期整改，如果上一次出现的问题没有出现在这一次中，则上一次也是已整改

        if (lastCheckSummary != null) {
            String lastA26Msg = "", lastA27Msg = "", lastA20Msg = "";

            // 判断住人是否合格
            boolean lastA33OkFlag = false;
            String a33 = lastCheckSummary.getA33();
            if (StringUtils.isBlank(a33)) lastA33OkFlag = true;

            // 判断是否有灭火器
            boolean lastA44OkFlag = false;
            String a44 = lastCheckSummary.getA44();
            if (!a44.equals("0")) lastA44OkFlag = true;

            // 判断电气线路是否合格
            boolean lastA46OkFlag = false;
            String a46 = lastCheckSummary.getA46();
            if (a46.equals("合格")) lastA46OkFlag = true;

            // 判断电动自行车情况是否合格
            boolean lastA47OkFlag = false;
            String a47 = lastCheckSummary.getA47();
            if (a47.equals("无")) lastA47OkFlag = true;

            // 判断高温加热是否合格
            boolean lastA48OkFlag = false;
            String a48 = lastCheckSummary.getA48();
            if (a48.equals("否")) lastA48OkFlag = true;

            // 判断是否存放易燃易爆危险品
            boolean lastA49OkFlag = false;
            String a49 = lastCheckSummary.getA49();
            if (a49.equals("否")) lastA49OkFlag = true;

            if (lastA33OkFlag && lastA44OkFlag && lastA46OkFlag && lastA47OkFlag && lastA48OkFlag && lastA49OkFlag) {
                lastA26Msg = "";
            } else {
                // 判断住人是否合格
                boolean a33OkFlag = false;
                String a33Cur = formSummary.getA33();
                if (StringUtils.isBlank(a33Cur)) a33OkFlag = true;

                // 判断是否又灭火器
                boolean a44OkFlag = false;
                String a44Cur = formSummary.getA44();
                if (!a44Cur.equals("0")) a44OkFlag = true;

                // 判断电气线路是否合格
                boolean a46OkFlag = false;
                String a46Cur = formSummary.getA46();
                if (a46Cur.equals("合格")) a46OkFlag = true;

                // 判断电动自行车情况是否合格
                boolean a47OkFlag = false;
                String a47Cur = formSummary.getA47();
                if (a47Cur.equals("无")) a47OkFlag = true;

                // 判断高温加热是否合格
                boolean a48OkFlag = false;
                String a48Cur = formSummary.getA48();
                if (a48Cur.equals("否")) a48OkFlag = true;

                boolean a49OkFlag = false;
                String a49Cur = formSummary.getA49();
                if (a49Cur.equals("否")) a49OkFlag = true;

                if (a33OkFlag && a44OkFlag && a46OkFlag && a47OkFlag && a48OkFlag && a49OkFlag) {
                    lastA26Msg = "已整改";
                } else {
                    lastA26Msg = "未整改";
                }
            }

            // 判断易燃易放是否合格
            String a61Last = lastCheckSummary.getA61(); // a61为限期整改
            if (StringUtils.isNotBlank(a61Last) && checkArrayListEmpty(a61Last)) {
                // 有限期整改的项目
                Set<String> lastProblemSet = Sets.newHashSet();

                List<String> a61LastList = JSONObject.parseArray(a61Last, String.class);
                if (a61LastList.size() > 2) {
                    String problem1 = a61LastList.get(3);
                    lastProblemSet.addAll(Sets.newHashSet(JSONObject.parseArray(problem1, String.class)));
                }
                if (a61LastList.size() > 3) {
                    String problem2 = a61LastList.get(4);
                    lastProblemSet.addAll(Sets.newHashSet(JSONObject.parseArray(problem2, String.class)));
                }
                lastProblemSet.remove("");

                if (lastProblemSet.size() == 0) {
                    lastA27Msg = "";
                } else {
                    String a61Cur = formSummary.getA61();
                    if (StringUtils.isNotBlank(a61Cur)) {
                        Set<String> curProblemSet = Sets.newHashSet();
                        List<String> a61CurList = JSONObject.parseArray(a61Cur, String.class);
                        if (a61CurList.size() > 2) {
                            String problemCur1 = a61CurList.get(3);
                            curProblemSet.addAll(Sets.newHashSet(JSONObject.parseArray(problemCur1, String.class)));
                        }

                        if (a61CurList.size() > 3) {
                            String problemCur2 = a61CurList.get(4);
                            curProblemSet.addAll(Sets.newHashSet(JSONObject.parseArray(problemCur2, String.class)));
                        }

                        curProblemSet.remove("");

                        // 存在之前，不存在之后，说明整改已经完成
                        Collection<String> notRectifyColl = CollUtil.intersection(curProblemSet, lastProblemSet);
                        if (notRectifyColl.size() == 0) {
                            lastA27Msg = "已整改";
                        } else {
                            lastA27Msg = "未整改";
                        }
                    }
                }
            }

            if (StringUtils.isBlank(formSummary.getA61())
                    || !checkArrayListEmpty(formSummary.getA61())) {
                lastA27Msg = "已整改";
            }

            lastCheckSummary.setA26(lastA26Msg);
            lastCheckSummary.setA27(lastA27Msg);
        }


        boolean a61HaveRiskFlag = false;
        if (StringUtils.isNotBlank(formSummary.getA61()) && checkArrayListEmpty(formSummary.getA61())) {
            List<String> a61List = JSONObject.parseArray(formSummary.getA61(), String.class);
            for (String a61Item : a61List) {
                List<String> a61ItemList = JSONObject.parseArray(a61Item, String.class);
                if (a61List.size() > 0) {
                    a61HaveRiskFlag = true;
                    break;
                }
            }
        }

        boolean a60HaveRiskFlag = false;
        if (StringUtils.isNotBlank(formSummary.getA60()) && checkArrayListEmpty(formSummary.getA60())) {
            List<String> a60List = JSONObject.parseArray(formSummary.getA60(), String.class);
            for (String a60Item : a60List) {
                List<String> a60ItemList = JSONObject.parseArray(a60Item, String.class);
                if (a60ItemList.size() > 0) {
                    a60HaveRiskFlag = true;
                    break;
                }
            }
        }
        if (a61HaveRiskFlag) {
            if (a60HaveRiskFlag) {
                formSummary.setA27("已整改");
            }
        }
        // 需求：如果a61为空值且a60有值时，则填写【已整改】。如果a61有值且a60也有值则填写【未整改】 add by LJT 2024-01-16
        if ((StringUtils.isBlank(formSummary.getA61()) || !checkArrayListEmpty(formSummary.getA61()))
                && (StringUtils.isNotEmpty(formSummary.getA60()) && checkArrayListEmpty(formSummary.getA60()))) {
            formSummary.setA27("已整改");
        } else if (StringUtils.isNotEmpty(formSummary.getA61()) && checkArrayListEmpty(formSummary.getA61())
                && StringUtils.isNotEmpty(formSummary.getA60()) && checkArrayListEmpty(formSummary.getA60())) {
            formSummary.setA27("未整改");
        }
    }

    @Override
    public String getDownloadTemplateFormExcelType(String sqfwId, Integer fileIndex, String excelType, String isWord, String serviceType, String companyName) {
        if (StringUtils.isNotBlank(sqfwId) && StringUtils.isBlank(serviceType)) {
            Sqfw_servicerecord sqfwServicerecord = sqfwServicerecordService.fetch(sqfwId);
            if (null == sqfwServicerecord) {
                throw new ServiceException("未查询到服务信息！");
            }
            serviceType = sqfwServicerecord.getType();
        }
        SupportBusinessTypeEnum serviceTypeInfo = SupportBusinessTypeEnum.getCodeByName(serviceType);
        String pathUrl = null;
        if (null == serviceTypeInfo) throw new ServiceException("暂无此事件类型");
        switch (serviceTypeInfo) {
            case MEET_RECORD:
                //会议记录模板
                pathUrl = generateMeetingRecordTemplate(sqfwId, isWord);
                break;
            case PUBLIC_SECURITY:
                //社会治安模板
                pathUrl = generatePublicSecurityTemplateForApp(sqfwId, fileIndex, isWord);
                break;
            case SAFE_CHECK:
                //安全排查模板
                pathUrl = generateFireHiddenCollectionTemplateForApp(sqfwId, null, fileIndex, "isTemplate", isWord, companyName);
                break;
            case SAFETY_CHECK:
                //安全排查模板
                pathUrl = generateFireHiddenCollectionTemplateForApp(sqfwId, null, fileIndex, "isTemplate", isWord, companyName);
                break;
            case RUBBISH_CLASSIFY:
                //垃圾分类模板
                pathUrl = generateRubbishClassifyTemplateExcelForApp(sqfwId, null, isWord);
                break;
            case HOUSE_SURVEY_FORM:
                //入户调查模板
                pathUrl = generateHouseSurveyTemplateExcelForApp(sqfwId, excelType, null, isWord, "isTemplate");
                break;
            default:
                throw new ServiceException("没有此事件类型！");
        }
        return pathUrl;
    }

    private String generateMeetingRecordTemplate(String sqfwId, String isWord) {
        String street = null;
        //zhangp 2023-12-08 存在服务从服务取数据，不存在就取当前用户信息
        if (StringUtils.isNotBlank(sqfwId)) {
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
            street = serviceRecord.getCounty();
        } else {
            Sys_user user = sysUserService.fetch(SecurityUtil.getUserId());
            street = user.getCounty();
        }
        // 1 构建内容体
        Map<String, Object> excelMap = Maps.newHashMap();
        excelMap.put("Street", street);
        excelMap.put("list", Lists.newArrayList());
        //String fileName = String.format("%s%s%s", "Excel", "会议记录台账", DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
        String fileName = DownLoadFileNameEnum.MEETING_RECORD.getName();

        // 2 上传文档
        String url = FromSummaryComponent.generateExcelLedger(excelMap, "meetingMinutes/meeting_minutes_ledger_template.xlsx", fileName, SupportBusinessTypeEnum.MEET_RECORD.getName());
        log.info("statisticalExcelLedger info res: {}", url);
        return url;
    }

    private String generateFireHiddenCollectionTemplateForApp(String sqfwId, String workOrderId, Integer fileIndex, String isTemplate, String isWord, String companyName) {
        if (StringUtils.isNotBlank(isWord) && "word".equals(isWord)) {
            //下载word
            return generateFireHiddenTemplateWordForApp(sqfwId, fileIndex);
        } else {
            //下载excel
            String fileNameSuffix = DateUtil.format(new Date(), "yyyyMMddHHmmss");
            List<String> sqfwIdList = Lists.newArrayList();
            if (StringUtils.isBlank(sqfwId)) {
                isTemplate = "isTemplate-web";
            } else {
                sqfwIdList = Lists.newArrayList(sqfwId);
            }

            return generateFireHiddenCollectionExcelForApp(sqfwIdList, workOrderId, SecurityUtil.getUserId(), fileIndex, fileNameSuffix, isTemplate, companyName);
        }
    }

    @Override
    public String downloadTemplateForIndex(Integer fileIndex, String isWord, String unitName) {
        Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
        unitName = StringUtils.isBlank(unitName) ? sysUser.getUnitName() : unitName;
        // word 模板下载
        if (StringUtils.isNotBlank(isWord) && "word".equals(isWord)) {
            // 威清门、云潭街道word模板下载
            FireHiddenOfficeWordDTO wordDTO = new FireHiddenOfficeWordDTO();
            wordDTO.setIndex(fileIndex);
            wordDTO.setUnitName(unitName);
            wordDTO.setCity(sysUser.getCity());
            wordDTO.setCounty(sysUser.getCounty());
            wordDTO.setCommunity(sysUser.getCommunity());
            return FireHiddenOfficeFactory.createWordTemplate(wordDTO);
        } else { // excel模板下载
            // 短信模板下载
            if (fileIndex == 400) {
                return SmsMsgExcelUtils.downExcel(new ArrayList<>());
            }

            FireHiddenExcelParamSQDTO fireHiddenExcelParamSQDTO = new FireHiddenExcelParamSQDTO();
            fireHiddenExcelParamSQDTO.setUserId(SecurityUtil.getUserId());
            fireHiddenExcelParamSQDTO.setFileIndex(fileIndex);
            fireHiddenExcelParamSQDTO.setCompleteUnitName(unitName);
            return FireHiddenExcelFactory.downExcelTemplate(fireHiddenExcelParamSQDTO);
        }
    }


    private String generateFireHiddenTemplateWordForApp(String sqfwId, int index) {
        Sqfw_servicerecord sqfwServicerecord = this.sqfwServicerecordService.fetch(sqfwId);
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "=", sqfwId).and("type", "=", SqfwFormSummaryConstants.safety_check);
        List<Sqfw_formSummary> sqfwFormSummaryList = query(cnd);
        String unitName = sqfwServicerecord.getCompanyName();
        GenerateWordAndPdfUrlVO wordUrlVO = new GenerateWordAndPdfUrlVO();

        if (unitName.contains("油榨街")) {
            //TODO 对应word模板下载
        } else if (unitName.contains("金元") || unitName.contains("润兴")) {
            //TODO 对应word模板下载
        } else if (unitName.contains("大营路")) {
            //对应模板链接
            String pathUrls = daYingLuWordTemplate(!sqfwFormSummaryList.isEmpty() ? sqfwFormSummaryList.get(0) : new Sqfw_formSummary());
            wordUrlVO.setWordUrl(pathUrls);
        } else if (unitName.contains(StreetEnum.WEI_QING_MEN_STREET.getName())) {
            Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
            FireHiddenOfficeWordDTO wordDTO = new FireHiddenOfficeWordDTO();
            wordDTO.setIndex(index);
            wordDTO.setUnitName(sysUser.getUnitName());
            wordDTO.setCity(sysUser.getCity());
            wordDTO.setCounty(sysUser.getCounty());
            wordDTO.setCommunity(sysUser.getCommunity());
            return FireHiddenOfficeFactory.createWordTemplate(wordDTO);
        } else if (unitName.contains("云潭街道")) {
            //宇虹社区
            //TODO 对应word模板下载
        } else {
            // 花果园 生成消防安全排查word
            //TODO 对应word模板下载
        }
        if (StringUtils.isBlank(wordUrlVO.getWordUrl())) {
            log.error("SqfwFormSummaryServiceImpl.generateFireHiddenTemplateWordForApp:安全排查下载模板失败！");
            throw new ServiceException("下载模板失败！");
        } else {
            return wordUrlVO.getWordUrl();
        }

    }

    private String daYingLuWordTemplate(Sqfw_formSummary formSummary) {
        Sqfw_formSummary sqfwFormSummary = new Sqfw_formSummary();
        // 一共可能生成4个word
        List<String> pathUrlList = Lists.newArrayList();
        String a5 = formSummary.getA5();
        if (BigPlaceInfoConstants.bigPlaceInfoSet.contains(a5)) {
            // 生成云岩区消防安全风险隐患排查整治台账
            GenerateWordAndPdfUrlVO resultVO = createSafetyRiskStandingBook(sqfwFormSummary, formSummary.getType());
            pathUrlList.add(resultVO.getWordUrl());
        } else {
            // 云岩区小型经营性场所消防安全综合治理
            GenerateWordAndPdfUrlVO resultVO = createSmallBusinessPremisesSafetyGoverRecordTemplate(sqfwFormSummary, formSummary.getType());
            pathUrlList.add(resultVO.getWordUrl());

            // 餐饮经营服务场所消防安全巡查记录
            GenerateWordAndPdfUrlVO wordVO1 = createCateringPremisesSafetyVisRecordTemplate(sqfwFormSummary, formSummary.getType());
            pathUrlList.add(wordVO1.getWordUrl());

            // 瓶装液化燃气用户安全检查登录表
            GenerateWordAndPdfUrlVO wordVO2 = createCateringPremisesSafetyVisRecordTemplate(sqfwFormSummary, formSummary.getType());
            pathUrlList.add(wordVO2.getWordUrl());

            // 生成视频监督协管员日常检查记录
            GenerateWordAndPdfUrlVO wordVO3 = createCateringPremisesSafetyVisRecordTemplate(sqfwFormSummary, formSummary.getType());
            pathUrlList.add(wordVO3.getWordUrl());

            //wordAndUpload

        }
        return String.join(",", pathUrlList);
    }

    private GenerateWordAndPdfUrlVO createBottleGasSafetyRegistrationTemplate(Sqfw_formSummary formSummary, String type) {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("area", null);
        paramMap.put("fillDateStr", DateUtil.format(new Date(), "yyyy-MM-dd"));
        paramMap.put("a1", formSummary.getA1());
        paramMap.put("a2", formSummary.getA2());
        paramMap.put("a11", formSummary.getA11());
        paramMap.put("a8", formSummary.getA8());
        paramMap.put("a53", formSummary.getA53());
        paramMap.put("a14", formSummary.getA14());
        paramMap.put("a3", formSummary.getA3());

        String a23 = formSummary.getA23();
        List<String> a23List = Lists.newArrayList();
        if (StringUtils.isBlank(a23)) {
            for (int i = 0; i < 27; i++) a23List.add("否");  // 因为a23有可能不传值，所以对于没有传值的需要进行初始化
        } else a23List = Lists.newArrayList(a23.split(","));
        for (int a23Index = 0; a23Index < a23List.size(); a23Index++) {
            String keywordPrefix = "a23_";
            String keyword = (a23Index + 1) + "";
            String value = a23List.get(a23Index);

            keyword = keywordPrefix + keyword;
            boolean valueBool = value.equals("是");
            paramMap.put(keyword, valueBool);
        }

        paramMap.put("a20", formSummary.getA20());
        paramMap.put("a25", formSummary.getA25());

        paramMap.put("a19", null);
        // 检查人签名等
        addWordUserSignature(paramMap, "a18NoSig", "a18Sigs", "a18Sig",
                Lists.newArrayList(), Lists.newArrayList(), 1.0F);
        return wordAndUpload(paramMap, "daYingLu/bottleGasSafetyRegistration.docx", "瓶装野花燃气用户安全检查登记表", type);
    }

    private static GenerateWordAndPdfUrlVO createFoodSupInsRecord(Sqfw_formSummary formSummary, String type) {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("a1", formSummary.getA1());
        paramMap.put("a2", formSummary.getA2());
        paramMap.put("a3", formSummary.getA3());
        paramMap.put("a8", formSummary.getA8());
        paramMap.put("a28", formSummary.getA28());
        paramMap.put("fillDateStr", DateUtil.format(formSummary.getFillDate(), "yyyy-MM-dd"));

        String a62 = formSummary.getA62();
        if (StringUtils.isBlank(a62)) {
            List<List<List<String>>> a62List = Lists.newArrayList();
            for (int i = 0; i < 4; i++) {
                List<List<String>> a62ItemList = Lists.newArrayList();
                for (int j = 0; j < 32; j++) {
                    List<String> secList = Lists.newArrayList();
                    a62ItemList.add(secList);
                }
                a62List.add(a62ItemList);
            }
            a62 = JSONObject.toJSONString(a62List);
        }
        List<String> a62List = Lists.newArrayList(Splitter.on(",").split(a62));
        for (int a64Index = 0; a64Index < a62List.size(); a64Index++) {
            String key = "a62_" + (a64Index + 1);
            String value = a62List.get(a64Index);
            boolean boolValue = true;
            if (StringUtils.isNotBlank(value)) boolValue = value.equals("是");

            paramMap.put(key, boolValue);
        }
        paramMap.put("a19", null);
        // 检查人签名等
        addWordUserSignature(paramMap, "a18NoSig", "a18Sigs", "a18Sig",
                Lists.newArrayList(), Lists.newArrayList(), 1.0F);
        return wordAndUpload(paramMap, "daYingLu/foodSupInsRecord.docx", "云岩区视频监督协管员日常检查记录表", type);
    }

    private GenerateWordAndPdfUrlVO createCateringPremisesSafetyVisRecordTemplate(Sqfw_formSummary formSummary, String type) {

        Map<String, Object> paramMap = Maps.newHashMap();
        Date fillDate = new Date();
        int fillDateYear = DateUtil.year(fillDate);
        int fillDateMonth = DateUtil.month(fillDate) + 1;
        int fillDateDay = DateUtil.dayOfMonth(fillDate);
        paramMap.put("fillDateYear", fillDateYear);
        paramMap.put("fillDateMonth", fillDateMonth);
        paramMap.put("fillDateDay", fillDateDay);
        paramMap.put("a1", formSummary.getA1());
        paramMap.put("a2", formSummary.getA2());
        paramMap.put("a3", formSummary.getA3());
        paramMap.put("a8", formSummary.getA8());

        String a23 = formSummary.getA23();
        List<String> a23List = Lists.newArrayList();
        if (StringUtils.isBlank(a23)) {
            for (int i = 0; i < 27; i++) a23List.add("否");  // 因为a23有可能不传值，所以对于没有传值的需要进行初始化
        } else {
            a23List = Lists.newArrayList(a23.split(","));
        }
        for (int a23Index = 0; a23Index < a23List.size(); a23Index++) {
            String paramNamePrefix = "a23_";
            String indexStr = a23List.get(a23Index);

            boolean indexBool = indexStr.equals("是");

            paramMap.put(paramNamePrefix + (a23Index + 1), indexBool);
        }

        String a60 = formSummary.getA60();
        if (StringUtils.isBlank(a60)) a60 = JSONObject.toJSONString(Lists.newArrayList()); // 有可能前端没有传值 所以这个步骤就是进行初始化
        List<String> a60List = JSONObject.parseArray(a60, String.class);
        String a60_4Str = "";
        if (a60List.size() > 5) {
            List<String> a60_6List = JSONObject.parseArray(a60List.get(5), String.class);
            a60_4Str = Joiner.on("、").join(a60_6List);
        }
        paramMap.put("a60_5", a60_4Str);

        // 巡查结果
        boolean visResult = false;

        String a61 = formSummary.getA61();
        if (StringUtils.isBlank(a61)) a61 = JSONObject.toJSONString(Lists.newArrayList());
        if (StringUtils.isBlank(a61)) {
            paramMap.put("a61_5", "");
            paramMap.put("a25Month", "");
            paramMap.put("a25Day", "");
        } else {
            String a61_5Str = "";
            List<String> a61List = JSONObject.parseArray(a61, String.class);
            if (a61List.size() > 5) {
                Set<String> a61_5Set = Sets.newHashSet(JSONObject.parseArray(a61List.get(5), String.class));
                a61_5Set.remove("");
                if (a61_5Set.size() == 0) visResult = true;
                a61_5Str = Joiner.on("、").join(a61_5Set);
            }
            paramMap.put("a61_5", a61_5Str);
        }

        // 复查情况
        // 使用上一次a61的字段和这一次a61的字段进行对比
        // 1、如果上一次的a61是空时（说明上一次的巡查时没有问题的） 不用生成复查表格
        // 2、否则将此次的a61对比上一次的a61，如果上一次出现的这一次没有出现则是整改完成项
        //    如果上一次出现的这一次还出现，将这些填充到复查情况的未整改项处

        // 初始化复查数据
        paramMap.put("fillDateMonthSec", "");
        paramMap.put("fillDateDaySec", "");
        paramMap.put("a61Rectify", "");
        paramMap.put("a61NotRectify", "");

        paramMap.put("a18NoSigSec", "");
        paramMap.put("a18SigsSec", null);
        paramMap.put("a19Sec", null);

        paramMap.put("visResult", visResult);
        if (visResult) {
            paramMap.put("a25Month", "");
            paramMap.put("a25Day", "");
        } else {
            String a25 = formSummary.getA25();
            if (StringUtils.isNotBlank(a25)) {
                DateTime a25DateTime = DateUtil.parse(a25, "yyyy-MM-dd");
                paramMap.put("a25Month", a25DateTime.month() + 1);
                paramMap.put("a25Day", a25DateTime.dayOfMonth());
            } else {
                // 因为a25有可能误传，所以这句话是为了避免出现问题
                paramMap.put("a25Month", "");
                paramMap.put("a25Day", "");
            }
        }
        // 检查人签名等
        addWordUserSignature(paramMap, "a18NoSig", "a18Sigs", "a18Sig",
                Lists.newArrayList(), Lists.newArrayList(), 1.0F);
        paramMap.put("a19", null);

        return wordAndUpload(paramMap, "daYingLu/cateringPremisesSafetyVistRecord.docx", "云岩区餐饮经营服务场所消防安全巡查记录", type);
    }

    private GenerateWordAndPdfUrlVO createSmallBusinessPremisesSafetyGoverRecordTemplate(Sqfw_formSummary formSummary, String type) {
        Map<String, Object> smallBPParam = Maps.newHashMap();
        smallBPParam.put("unitName", formSummary.getUnitName());
        smallBPParam.put("fillDateStr", DateUtil.format(new Date(), "yyyy年MM月dd日HH时"));
        smallBPParam.put("a1", formSummary.getA1());
        smallBPParam.put("a3", formSummary.getA3());
        smallBPParam.put("a2", formSummary.getA2());
        smallBPParam.put("a8", formSummary.getA8());
        smallBPParam.put("a5", formSummary.getA5());
        smallBPParam.put("a6", formSummary.getA6());

        // 是否搭建夹层信息
        boolean a29_1 = false, a29_2 = false, a29_3 = false, a29_4 = false;
        String a29 = formSummary.getA29();
        if (StringUtils.isNotBlank(a29)) {
            if (a29.equals("否")) {
                a29_4 = true;
            } else {
                a29_1 = true;
                a29_2 = a29.contains("库房");
                a29_3 = a29.contains("居住");
            }
        }
        smallBPParam.put("a29_1", a29_1);
        smallBPParam.put("a29_2", a29_2);
        smallBPParam.put("a29_3", a29_3);
        smallBPParam.put("a29_4", a29_4);
        smallBPParam.put("a30", formSummary.getA30());

        // 夹层楼板信息
        String a31 = formSummary.getA31();
        smallBPParam.put("a31", a31);

        // 楼梯建筑材料
        boolean a32_1 = false, a32_3 = false;
        String a32_2 = "", a32_4 = "";

        String a32 = formSummary.getA32();

        smallBPParam.put("a32_1", a32_1);
        smallBPParam.put("a32_2", a32_2);
        smallBPParam.put("a32_3", a32_3);
        smallBPParam.put("a32_4", a32_4);

        // 是否住人 当a33-a38有值为是的时候都是住人的
        boolean reside_1 = false, reside_2 = true;

        // 居住人数
        smallBPParam.put("a34", formSummary.getA34());
        // 层数
        smallBPParam.put("a35", formSummary.getA35());

        boolean a36_1 = false, a36_2 = false, a36_3 = false, a36_4 = false, a36_5 = false;
        String a36 = formSummary.getA36();
        if (StringUtils.isNotBlank(a36)) {
            if (a36.equals("符合要求")) {
                a36_1 = true;
                a36_2 = true;
                a36_3 = true;
            }

            if (a36.equals("设置卷帘门、铁栅栏等")) {
                a36_1 = true;
                a36_2 = true;
                a36_4 = true;
            }

            if (a36.equals("无")) {
                a36_5 = true;
            }
        }
        smallBPParam.put("a36_1", a36_1);
        smallBPParam.put("a36_2", a36_2);
        smallBPParam.put("a36_3", a36_3);
        smallBPParam.put("a36_4", a36_4);
        smallBPParam.put("a36_5", a36_5);

        String a37 = formSummary.getA37();
        boolean a37_1 = false, a37_2 = false, a37_3 = false, a37_4 = false;
        if (StringUtils.isNotBlank(a37)) {
            if (a37.equals("符合要求")) {
                a37_1 = true;
                a37_2 = true;
            }

            if (a37.equals("设置防盗窗等")) {
                a37_1 = true;
                a37_3 = true;
            }

            if (a37.equals("无")) {
                a37_4 = true;
            }
        }
        smallBPParam.put("a37_1", a37_1);
        smallBPParam.put("a37_2", a37_2);
        smallBPParam.put("a37_3", a37_3);
        smallBPParam.put("a37_4", a37_4);

        // 住人形式
        String a33 = formSummary.getA33();
        if (StringUtils.isBlank(a33)) a33 = "";
        String a33_2 = "";
        smallBPParam.put("a33", a33);
        smallBPParam.put("a33_2", a33_2);


        // 经营与住区域是否有防火分隔
        String a38 = formSummary.getA38();
        if (StringUtils.isBlank(a38)) a38 = "";
        boolean a38_1 = false, a38_3 = false;
        String a38_2 = "", a38_4 = "";

        smallBPParam.put("a38_1", a38_1);
        smallBPParam.put("a38_2", a38_2);
        smallBPParam.put("a38_3", a38_3);
        smallBPParam.put("a38_4", a38_4);

        if (StringUtils.isNotBlank(formSummary.getA34())) {
            reside_1 = true;
            reside_2 = false;
        }
        if (StringUtils.isNotBlank(formSummary.getA35())) {
            reside_1 = true;
            reside_2 = false;
        }
        if (StringUtils.isNotBlank(a33)) {
            reside_1 = true;
            reside_2 = false;
        }
        if (StringUtils.isNotBlank(a38)) {
            reside_1 = true;
            reside_2 = false;
        }
        smallBPParam.put("reside_1", reside_1);
        smallBPParam.put("reside_2", reside_2);

        // 火灾自动报警系统
        String a41 = formSummary.getA41();
        if (StringUtils.isBlank(a41)) a41 = "";
        boolean a41_1 = false, a41_2 = false;
        String a41_3 = "";
        if (a41.equals("有")) {
            a41_1 = true;
        }
        if (a41.equals("无")) {
            a41_2 = true;
        }

        smallBPParam.put("a41_1", a41_1);
        smallBPParam.put("a41_2", a41_2);
        smallBPParam.put("a41_3", a41_3);

        // 自动喷水灭水系统
        String a42 = formSummary.getA42();
        if (StringUtils.isBlank(a42)) a42 = "";
        boolean a42_1 = false, a42_2 = false;
        String a42_3 = "";
        if (a42.equals("有")) {
            a42_1 = true;
        }
        if (a42.equals("无")) {
            a42_2 = true;
        }

        smallBPParam.put("a42_1", a42_1);
        smallBPParam.put("a42_2", a42_2);
        smallBPParam.put("a42_3", a42_3);

        // 室内消火栓
        String a43 = formSummary.getA43();
        if (StringUtils.isBlank(a43)) a43 = "";
        boolean a43_1 = false, a43_2 = false;
        String a43_3 = "";
        if (a43.equals("有")) {
            a43_1 = true;
        }
        if (a43.equals("无")) {
            a43_2 = true;
        }

        smallBPParam.put("a43_1", a43_1);
        smallBPParam.put("a43_2", a43_2);
        smallBPParam.put("a43_3", a43_3);

        // 灭火器
        boolean a44_1 = false, a44_3 = false;
        String a44_2 = "";
        String a44 = formSummary.getA44();
        if (StringUtils.isNotBlank(a44) && !a44.equals("0")) {
            a44_1 = true;
            a44_2 = a44;
        } else {
            a44_3 = true;
        }
        smallBPParam.put("a44_1", a44_1);
        smallBPParam.put("a44_2", a44_2);
        smallBPParam.put("a44_3", a44_3);

        // 消防设施情况其他
        smallBPParam.put("a45", formSummary.getA45());

        // 电器线路情况
        String a46 = formSummary.getA46();
        if (StringUtils.isBlank(a46)) a46 = "";

        boolean a46_1 = false, a46_2 = false, a46_3 = false, a46_4 = false, a46_5 = false;
        String a46_6 = "";

        smallBPParam.put("a46_1", a46_1);
        smallBPParam.put("a46_2", a46_2);
        smallBPParam.put("a46_3", a46_3);
        smallBPParam.put("a46_4", a46_4);
        smallBPParam.put("a46_5", a46_5);
        smallBPParam.put("a46_6", a46_6);

        // 电动自行车使用情况
        String a47 = formSummary.getA47();
        if (StringUtils.isBlank(a47)) a47 = "";

        boolean a47_1 = false, a47_2 = false, a47_3 = false, a47_4 = false, a47_5 = false;
        String a47_6 = "";

        smallBPParam.put("a47_1", a47_1);
        smallBPParam.put("a47_2", a47_2);
        smallBPParam.put("a47_3", a47_3);
        smallBPParam.put("a47_4", a47_4);
        smallBPParam.put("a47_5", a47_5);
        smallBPParam.put("a47_6", a47_6);

        // 是否使用明火、高温加热、取暖设备
        String a48 = formSummary.getA48();
        if (StringUtils.isBlank(a48)) a48 = "";
        boolean a48_1 = false, a48_2 = false, a48_4 = false;
        String a48_3 = "", a48_5 = "";

        smallBPParam.put("a48_1", a48_1);
        smallBPParam.put("a48_2", a48_2);
        smallBPParam.put("a48_3", a48_3);
        smallBPParam.put("a48_4", a48_4);
        smallBPParam.put("a48_5", a48_5);

        // 是否存放易燃易爆危险品
        String a49 = formSummary.getA49();
        if (StringUtils.isBlank(a49)) a49 = "";
        boolean a49_1 = false, a49_3 = false;
        String a49_2 = "", a49_4 = "";

        a49_4 = "";
        smallBPParam.put("a49_1", a49_1);
        smallBPParam.put("a49_2", a49_2);
        smallBPParam.put("a49_3", a49_3);
        smallBPParam.put("a49_4", a49_4);

        // 宣传教育培训
        smallBPParam.put("a21", formSummary.getA21());
        smallBPParam.put("a22", formSummary.getA22());

        smallBPParam.put("a20", formSummary.getA20());
        smallBPParam.put("a12", "");


        // 检查人签名等
        addWordUserSignature(smallBPParam, "a18NoSig", "a18Sigs", "a18Sig",
                Lists.newArrayList(), Lists.newArrayList(), 1.0F);
        smallBPParam.put("a19", null);

        return wordAndUpload(smallBPParam, "daYingLu/smallBusinessPremisesSafetyGoverRecord.docx", "云岩区小型生产经营性场所安全治理记录", type);

    }

    private GenerateWordAndPdfUrlVO createSafetyRiskStandingBook(Sqfw_formSummary formSummary, String formType) {
        Map<String, Object> paramMap = Maps.newHashMap();

        paramMap.put("a63", formSummary.getA63());
        paramMap.put("a1", formSummary.getA1());
        paramMap.put("fillDateStr", DateUtil.format(formSummary.getFillDate(), "yyyy-MM-dd"));
        paramMap.put("a3", formSummary.getA3());
        paramMap.put("a2", formSummary.getA2());
        paramMap.put("a8", formSummary.getA8());

        String a64 = formSummary.getA64();
        if (StringUtils.isBlank(a64)) a64 = JSONObject.toJSONString(Lists.newArrayList());
        List<String> a64List = JSONObject.parseArray(a64, String.class);
        String a64_1Str = a64List.get(0);
        List<String> a64_1List = JSONObject.parseArray(a64_1Str, String.class);
        for (int index = 0; index < a64_1List.size(); index++) {
            String key = "a64_" + (index + 1);
            String value = a64_1List.get(index);

            boolean boolValue = !value.equals("否");
            paramMap.put(key, boolValue);
        }
        paramMap.put("a20", formSummary.getA20());
        paramMap.put("a12", formSummary.getA12());

        String a25Str = "无";
        String a25 = formSummary.getA25();
        if (StringUtils.isNotBlank(a25)) {
            DateTime a25Date = DateUtil.parse(a25, "yyyy-MM-dd");
            long betweenDay = DateUtil.betweenDay(formSummary.getFillDate(), a25Date, true);
            if (betweenDay == 0) a25Str = "当天";
            else a25Str = betweenDay + "天";
        }
        paramMap.put("a25Str", a25Str);
        paramMap.put("a65", formSummary.getA65());

        PictureRenderData a19Pic = addWordPicture(formSummary.getA19(), 1.0F);
        paramMap.put("a19", a19Pic);
        // 检查人签名等
        addWordUserSignature(paramMap, "a18NoSig", "a18Sigs", "a18Sig",
                Lists.newArrayList(), Lists.newArrayList(), 1.0F);

        return wordAndUpload(paramMap, "daYingLu/safetyRiskRecStandingBook.docx", "云岩区视频监督协管员日常检查记录表", formType);
    }


    @Override
    public List<Integer> getDownloadExcelTypeFromApp(String sqfwId) {
        Sqfw_servicerecord sqfwServicerecord = this.sqfwServicerecordService.fetch(sqfwId);
        if (null == sqfwServicerecord) {
            throw new ServiceException("未查询到服务记录信息！");
        }
//        ServiceTypeEnum serviceTypeInfo = ServiceTypeEnum.getServiceTypeByName(sqfwServicerecord.getType());
        SupportBusinessTypeEnum serviceTypeInfo = SupportBusinessTypeEnum.getCodeByName(sqfwServicerecord.getType());
        if (null == serviceTypeInfo) throw new ServiceException("没有此事件类型！");
        switch (serviceTypeInfo) {
            case MEET_RECORD:
                //会议记录
                return checkParamFromMeetingRecord(Lists.newArrayList(sqfwServicerecord.getId()), sqfwServicerecord.getCompanyName(), null, null, null);
            case PUBLIC_SECURITY:
                return checkParamFromPublicSecurity(Lists.newArrayList(sqfwServicerecord.getId()), sqfwServicerecord.getCompanyName(), null, null, null);
            case SAFE_CHECK:
                //安全排查数据检查
                return checkParamFromSafeCheck(Lists.newArrayList(sqfwServicerecord.getId()), sqfwServicerecord.getCompanyName(), null, null, null);
            case SAFETY_CHECK:
                //安全排查数据检查
                return checkParamFromSafeCheck(Lists.newArrayList(sqfwServicerecord.getId()), sqfwServicerecord.getCompanyName(), null, null, null);
            case RUBBISH_CLASSIFY:
                //垃圾分类数据检查
                return checkParamFromRubbishClassify(Lists.newArrayList(sqfwServicerecord.getId()), null, null, null);
            case HOUSE_SURVEY_FORM:
                //入户调查数据检查
                return checkParamFromHouseSurvey(sqfwServicerecord.getId(), null, null, null);
            default:
                throw new ServiceException("没有此事件类型！");
        }
    }

    private List<Integer> checkParamFromMeetingRecord(List<String> sqfwIdList, String companyName, String isAdmin, Sqfw_formSummaryForAdminVO bean, String queryEntry) {
        List<Integer> excelNameList = Lists.newArrayList();
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(isAdmin) && "isAdmin".equals(isAdmin)) {
            if ("query".equals(queryEntry)) {
                Criteria cri = meetingMinutesComponent.buildQueryCond(bean);
                cnd = Cnd.byCri((SimpleCriteria) cri);
            } else {
                if (sqfwIdList.isEmpty()) {
                    throw new ServiceException("请选择记录！");
                }
                cnd.and("id", "in", sqfwIdList);
            }
        } else {
            cnd.and("sqfw_id", "=", sqfwIdList.get(0));
        }
        cnd.and(Sqfw_formSummary::getType, "=", SupportBusinessTypeEnum.MEET_RECORD.getName());
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        String meetingRecordStatus = meetingMinutesComponent.generateExcelFile(formSummaryList, "isCheckData");
        if (StringUtils.isNotBlank(meetingRecordStatus) && meetingRecordStatus.equals("true")) {
            excelNameList.add(1);
        }
        return excelNameList;

    }

    @Override
    public List<Integer> getDownloadExcelTypeFromAdmin(List<SqfwSummaryPdfExcelCollForAdminDTO> conditionList, String serviceType, String companyName, Sqfw_formSummaryForAdminVO bean, String queryEntry) {
        List<String> sumIdList = conditionList.stream().map(SqfwSummaryPdfExcelCollForAdminDTO::getSumId).collect(Collectors.toList());
//        ServiceTypeEnum serviceTypeInfo = ServiceTypeEnum.getServiceTypeByName(serviceType);
        SupportBusinessTypeEnum serviceTypeInfo = SupportBusinessTypeEnum.getCodeByName(serviceType);
        if (null == serviceTypeInfo) throw new ServiceException("没有此事件类型！");
        switch (serviceTypeInfo) {
            case MEET_RECORD:
                //会议记录
                return checkParamFromMeetingRecord(sumIdList, companyName, "isAdmin", bean, queryEntry);
            case PUBLIC_SECURITY:
                //社会治安
                return checkParamFromPublicSecurity(sumIdList, companyName, "isAdmin", bean, queryEntry);
            case SAFE_CHECK:
                //安全排查数据检查
                return checkParamFromSafeCheck(sumIdList, companyName, "isAdmin", bean, queryEntry);
            case RUBBISH_CLASSIFY:
                //垃圾分类数据库检查
                return checkParamFromRubbishClassify(sumIdList, "isAdmin", bean, queryEntry);
            case HOUSE_SURVEY_FORM:
                //入户调查数据检查
                return checkParamFromHouseSurvey(String.join(",", sumIdList), "isAdmin", bean, queryEntry);
        }
        return Lists.newArrayList();
    }

    private List<Integer> checkParamFromPublicSecurity(List<String> sqfwIdList, String companyName, String isAdmin, Sqfw_formSummaryForAdminVO bean, String queryEntry) {
        List<Integer> excelNameList = Lists.newArrayList();
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(isAdmin) && "isAdmin".equals(isAdmin)) {
            if ("query".equals(queryEntry)) {
                //构建参数
                StreetEnum streetType = StreetEnum.getStreetType(companyName);
                if (null == streetType) streetType = DA_YING_LU_STREET;
                Criteria cri = safeCheckBuildQueryCond(bean, streetType);
                cnd = Cnd.byCri((SimpleCriteria) cri);
            } else {
                if (sqfwIdList.isEmpty()) {
                    throw new ServiceException("请选择记录！");
                }
                cnd.and("id", "in", sqfwIdList);
            }
        } else {
            cnd.and("sqfw_id", "=", sqfwIdList.get(0));
        }

        cnd.and("type", "=", SqfwFormSummaryConstants.public_security);
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        if (formSummaryList.isEmpty()) return excelNameList;
        FireHiddenExcelParamDaYingLuSQDTO excelParamDaYingLuSQDTO = new FireHiddenExcelParamDaYingLuSQDTO();
        excelParamDaYingLuSQDTO.setFormSummaryList(formSummaryList);
        String publicSecurityStatus = DaYingLuStreetPublicSecurityExcelUtils.publicSecurityStandingBook(excelParamDaYingLuSQDTO, "isCheckData");
        if (StringUtils.isNotBlank(publicSecurityStatus) && publicSecurityStatus.equals("true")) {
            excelNameList.add(DaYingLuExcelType.PUBLIC_SECURITY_STANDING_BOOK.getCode());
        }
        return excelNameList;
    }

    private List<Integer> checkParamFromHouseSurvey(String sqfdId, String isAdmin, Sqfw_formSummaryForAdminVO bean, String queryEntry) {

        List<Integer> excelNameList = Lists.newArrayList();
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(isAdmin) && "isAdmin".equals(isAdmin)) {
            if ("query".equals(queryEntry)) {
                cnd = sqfwCheckRecordForAdminService.buildCndParam(bean, bean.getPageOrderName(), bean.getPageOrderBy());
            } else {
                if (StringUtils.isBlank(sqfdId)) {
                    throw new ServiceException("请选择记录！");
                }
                cnd.and("id", "in", Lists.newArrayList(sqfdId.split(",")));
            }
        } else {
            cnd.and("sqfw_id", "=", sqfdId);
        }
        cnd.and("type", "=", SqfwFormSummaryConstants.house_survey_form);
        cnd.orderBy("fill_date", "asc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        if (formSummaryList.isEmpty()) return excelNameList;
        //zhangp 2023-12-19 根据枚举类型检测文档数据
        List<HouseSurveyEnum> houseSurveyEnums = List.of(HouseSurveyEnum.values());
        for (HouseSurveyEnum he : houseSurveyEnums) {
            if (he.getName().equals(HouseSurveyEnum.WINTER_PARTROL.getName())) {
                continue;
            }
            if (!excelNameList.contains(he.getCode())) {
                String isCheckStatus = CommonComponent.generateHouseSurveyFormExcelForApp(null, formSummaryList, he.getName(), null, null, null, "isCheckData");
                if (StringUtils.isNotBlank(isCheckStatus) && "true".equals(isCheckStatus)) {
                    excelNameList.add(he.getCode());
                }
            }
        }

        return excelNameList;
    }

    private List<Integer> checkParamFromRubbishClassify(List<String> sqfwIdList, String isAdmin, Sqfw_formSummaryForAdminVO bean, String queryEntry) {
        List<Integer> excelNameList = Lists.newArrayList();
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(isAdmin) && "isAdmin".equals(isAdmin)) {
            if ("query".equals(queryEntry)) {
                SimpleCriteria cri = wasteClassificationService.buildQueryCond(bean);
                cnd = Cnd.byCri(cri);
            } else {
                if (sqfwIdList.isEmpty()) {
                    throw new ServiceException("请选择记录！");
                }
                cnd.and("id", "in", sqfwIdList);
            }
        } else {
            cnd.and("sqfw_id", "=", sqfwIdList.get(0));
        }

        cnd.and("type", "=", SqfwFormSummaryConstants.refuse_classify);
        cnd.orderBy("fill_date", "asc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        RefuseClassifyExcelParamDTO excelParamDTO = new RefuseClassifyExcelParamDTO();
        excelParamDTO.setFormSummaryList(formSummaryList);
        if (formSummaryList.isEmpty()) {
            return excelNameList;
        }
        List<String> idList = formSummaryList.stream().map(Sqfw_formSummary::getSqfwId).collect(Collectors.toList());
        Cnd yuHongSR = Cnd.NEW();
        yuHongSR.and("id", "in", idList).and("company_name", "like", "%宇虹%");
        List<Sqfw_servicerecord> sqfwServicerecordList = sqfwServicerecordService.query(yuHongSR);
        if (idList.size() == sqfwServicerecordList.size()) {
            excelParamDTO.setCompleteUnitName(sqfwServicerecordList.get(0).getCompanyName());
            String rubbishStatus = RefuseClassifyOfficeUtils.createRefuseClassifyExcelYuHongSQ(excelParamDTO, "isCheckData");
            if (StringUtils.isNotBlank(rubbishStatus) && "true".equals(rubbishStatus)) {
                excelNameList.add(1);
            }
        } else if (sqfwServicerecordList.isEmpty()) {
            excelParamDTO.setCompleteUnitName(formSummaryList.get(0).getUnitName());
            String rubbishStatus = RefuseClassifyOfficeUtils.createRefuseClassifyExcel(excelParamDTO, "isCheckData");
            if (StringUtils.isNotBlank(rubbishStatus) && "true".equals(rubbishStatus)) {
                excelNameList.add(RubbishClassPatrolEnum.RUBBISH_CLASS_LIST.getCode());
            }
        } else {
            excelParamDTO.setCompleteUnitName(sqfwServicerecordList.get(0).getCompanyName());
            String rubbishStatus = RefuseClassifyOfficeUtils.createRefuseClassifyExcelYuHongSQ(excelParamDTO, "isCheckData");
            if (StringUtils.isNotBlank(rubbishStatus) && "true".equals(rubbishStatus)) {
                excelNameList.add(RubbishClassPatrolEnum.RUBBISH_CLASS_LIST.getCode());
            }
            if (!excelNameList.contains(RubbishClassPatrolEnum.RUBBISH_CLASS_LIST.getCode())) {
                excelParamDTO.setCompleteUnitName(RubbishClassPatrolEnum.RUBBISH_CLASS_LIST.getName());//公司名称不包含宇虹
                rubbishStatus = RefuseClassifyOfficeUtils.createRefuseClassifyExcel(excelParamDTO, "isCheckData");
                if (StringUtils.isNotBlank(rubbishStatus) && "true".equals(rubbishStatus)) {
                    excelNameList.add(RubbishClassPatrolEnum.RUBBISH_CLASS_LIST.getCode());
                }
            }

        }
        /*Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(formSummaryList.get(0).getSqfwId());
        excelParamDTO.setCompleteUnitName(serviceRecord.getCompanyName());

        String rubbishStatus = RefuseClassifyOfficeUtils.createRefuseClassifyExcel(excelParamDTO, "isCheckData");
        if (StringUtils.isNotBlank(rubbishStatus) && "true".equals(rubbishStatus)) {
            excelNameList.add(1);
        }*/
        return excelNameList;
    }

    private List<Integer> checkParamFromSafeCheck(List<String> sqfwIdList, String companyName, String isAdmin, Sqfw_formSummaryForAdminVO bean, String queryEntry) {
        StreetEnum streetType = null;
        Cnd cnd = Cnd.NEW();
        if (StringUtils.isNotBlank(isAdmin) && "isAdmin".equals(isAdmin)) {
            streetType = StreetEnum.getStreetType(companyName);
            if ("query".equals(queryEntry)) {
                //构建参数
                Criteria cri = safeCheckBuildQueryCond(bean, streetType);
                cnd = Cnd.byCri((SimpleCriteria) cri);
            } else {
                if (sqfwIdList.isEmpty()) {
                    throw new ServiceException("请选择记录！");
                }
                cnd.and("id", "in", sqfwIdList);
            }
        } else {
            cnd.and("sqfw_id", "=", sqfwIdList.get(0));
            Sys_user sysUser = sysUserService.fetch(SecurityUtil.getUserId());
            streetType = StreetEnum.getStreetType(sysUser.getCounty());

        }

        cnd.and("type", "=", SqfwFormSummaryConstants.safety_check);
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        if (null == streetType) {
            if (!formSummaryList.isEmpty()) {
                return Lists.newArrayList(1);
            } else {
                return Lists.newArrayList();
            }

        }
        switch (streetType) {
            case DA_YING_LU_STREET:
                //大营路街道
                return checkParamDaYingLuStreet(formSummaryList, companyName);
            case YUN_TAN_STREET:
                //云潭街道
                return checkParamYunTanStreet(formSummaryList, companyName);
            case JIN_YANG_STREET:
                //金阳街道
                return checkParamJinYangStreet(formSummaryList, companyName);
            case WEI_QING_MEN_STREET:
                //威清路街道
                return checkParamWeiQingMenStreet(bean, formSummaryList, companyName);
            case HUA_GUO_YUAN_STREET:
                //花果园
                return checkParamHuaGuoYuanStreet(formSummaryList, companyName);
            case YOU_ZHA_STREET:
                //油榨街
                return checkParamYouZhaStreet(formSummaryList, companyName);
        }

        return Lists.newArrayList();
    }


    /**
     * @param bean
     * @param streetType
     * @return
     */
    private Criteria safeCheckBuildQueryCond(Sqfw_formSummaryForAdminVO bean, StreetEnum streetType) {
        Cnd cnd;
        Criteria cri = null;

        switch (streetType) {
            case DA_YING_LU_STREET:
                //大营路街道
                cnd = sqfwSummaryForAdminService.buildDYLQueryParam(bean);
                cri = cnd.getCri();
                break;
            case YUN_TAN_STREET:
                //云潭街道
                cri = yunTanStreetService.buildQueryCond(bean);
                break;
            case JIN_YANG_STREET:
                //金阳街道
                cri = jinYangStreetService.buildQueryCond(bean);
                break;
            case WEI_QING_MEN_STREET:
                //威清路街道
                cnd = sqfwSummaryForAdminService.buildWQMQueryParam(bean);
                cri = cnd.getCri();
                break;
            case HUA_GUO_YUAN_STREET:
                //花果园街道
                cri = huaGuoYuanStreetService.buildQueryCond(bean);
                break;
            case YOU_ZHA_STREET:
                //油榨街
                cri = youZhaStreetService.buildQueryCond(bean);
                break;


        }
        return cri;
    }

    private List<Integer> checkParamHuaGuoYuanStreet(List<Sqfw_formSummary> formSummaryList, String companyName) {
        List<Integer> excelNameList = Lists.newArrayList();
        FireHiddenExcelParamWeiQingMenSQDTO excelParamWeiQingMenSQDTO = new FireHiddenExcelParamWeiQingMenSQDTO();
        excelParamWeiQingMenSQDTO.setFormSummaryList(formSummaryList);
        excelParamWeiQingMenSQDTO.setCompleteUnitName(companyName);
        // 隐患排查整治清单
        String dangerStatus = FireHiddenOfficeUtils.createFireHiddenExcel(excelParamWeiQingMenSQDTO, "isCheckData");
        if (StringUtils.isNotBlank(dangerStatus) && dangerStatus.equals("true")) {
            excelNameList.add(1);
        }
        return excelNameList;
    }

    private List<Integer> checkParamYouZhaStreet(List<Sqfw_formSummary> formSummaryList, String companyName) {
        List<Integer> excelNameList = Lists.newArrayList();
        FireHiddenExcelParamWeiQingMenSQDTO excelParamWeiQingMenSQDTO = new FireHiddenExcelParamWeiQingMenSQDTO();
        excelParamWeiQingMenSQDTO.setFormSummaryList(formSummaryList);
        excelParamWeiQingMenSQDTO.setCompleteUnitName(companyName);
        // 隐患排查整治清单
        String dangerStatus = FireHiddenOfficeUtils.createFireHiddenExcelYouZhaJieShiNanSQ(excelParamWeiQingMenSQDTO, "isCheckData");
        if (StringUtils.isNotBlank(dangerStatus) && dangerStatus.equals("true")) {
            excelNameList.add(1);
        }
        return excelNameList;
    }

    /**
     * 威清门街道是否能生成excel、pdf检查(是否有数据)
     *
     * @param formSummaryList
     * @return
     */
    public List<Integer> checkParamWeiQingMenStreet(List<Sqfw_formSummary> formSummaryList) {
        return checkParamWeiQingMenStreet(null, formSummaryList, "");
    }

    /**
     * 威清门街道是否能生成excel、pdf检查(是否有数据)
     *
     * @param formSummaryList
     * @return
     */
    private List<Integer> checkParamWeiQingMenStreet(Sqfw_formSummaryForAdminVO bean, List<Sqfw_formSummary> formSummaryList, String companyName) {
        List<Integer> excelNameList = Lists.newArrayList();
        //zhangp 2024-01-02 无数据时直接返回
        if (formSummaryList.isEmpty()) {
            return excelNameList;
        }
        FireHiddenExcelParamWeiQingMenSQDTO excelParamWeiQingMenSQDTO = new FireHiddenExcelParamWeiQingMenSQDTO();
        excelParamWeiQingMenSQDTO.setFormSummaryList(formSummaryList);
        excelParamWeiQingMenSQDTO.setCompleteUnitName(companyName);
        List<String> sumIds = formSummaryList.stream().map(Sqfw_formSummary::getId).collect(Collectors.toList());
        //zhangp 2023-12-18 根据枚举类型获取文档数检测数据
        //检测EXCEL
        List<WeiQingMenExcelType> weiQingMenExcelTypes = List.of(WeiQingMenExcelType.values());
        for (WeiQingMenExcelType we : weiQingMenExcelTypes) {
            excelParamWeiQingMenSQDTO.setFileIndex(we.getCode());
            String nineSmallStatus = sqfwSummaryForAdminService.weiQingMenStreetFireHiddenExcel(excelParamWeiQingMenSQDTO, sumIds,
                    "isCheckData", bean != null ? bean.getQueryTime() : null);
            //String nineSmallStatus = WeiQingMenStreetFireHiddenExcelUtils.createFireHiddenExcelSQ(excelParamWeiQingMenSQDTO, "isCheckData");
            if (StringUtils.isNotBlank(nineSmallStatus) && nineSmallStatus.equals("true")) {
                excelNameList.add(we.getCode());
            }
        }
        // ywm 检测pdf
        List<WeiQingMenPdfType> weiQingMenPdfTypes = List.of(WeiQingMenPdfType.values());
        for (WeiQingMenPdfType pdf : weiQingMenPdfTypes) {
            List<String> ids = formSummaryList.stream().map(Sqfw_formSummary::getId).collect(Collectors.toList());
            int code = pdf.getCode();
            //检测PDF
            String path = GeneratePdfConverge.downPdfConverge(StreetEnum.WEI_QING_MEN_STREET.getName(),
                    ids, code, "isCheckData");
            if (StringUtils.isNotBlank(path) && "true".equals(path)) {
                excelNameList.add(pdf.getCode());
            }
        }
        // 短信检测
        List<String> ids = formSummaryList.stream().map(Sqfw_formSummary::getId).collect(Collectors.toList());
        int total = sqfwSmsMsgService.dataCheck(ids);
        if (total > 0) excelNameList.add(400);

        return excelNameList;
    }

    /**
     * 金阳街道是否能生成excel检查
     *
     * @param formSummaryList
     * @return
     */
    private List<Integer> checkParamJinYangStreet(List<Sqfw_formSummary> formSummaryList, String companyName) {
        List<Integer> excelNameList = Lists.newArrayList();
        FireHiddenExcelParamJinYuanSQDTO excelParamJinYuanSQDTO = new FireHiddenExcelParamJinYuanSQDTO();
        excelParamJinYuanSQDTO.setFormSummaryList(formSummaryList);
        excelParamJinYuanSQDTO.setCompleteUnitName(companyName);
        //zhangp 2023-12-18 根据枚举类型获取文档数检测数据
        List<JinYangExcelType> jinYangExcelTypes = List.of(JinYangExcelType.values());
        for (JinYangExcelType je : jinYangExcelTypes) {
            excelParamJinYuanSQDTO.setFileIndex(je.getCode());
            VisAndInsForJinYangJieDaoExcelVO gasInspectionStatus = FireHiddenOfficeUtils.createFireHiddenExcelJinYuanSQ(excelParamJinYuanSQDTO, "isCheckData");
            if ("true".equals(gasInspectionStatus.getGasInsExcelUrl())) {
                excelNameList.add(je.getCode());
            }
            if ("true".equals(gasInspectionStatus.getGasRecExcelUrl())) {
                excelNameList.add(je.getCode());
            }
            if ("true".equals(gasInspectionStatus.getStandingBookExcelUrl())) {
                excelNameList.add(je.getCode());
            }
            if ("true".equals(gasInspectionStatus.getVisAndInsExcelUrl())) {
                excelNameList.add(je.getCode());
            }

        }
        return excelNameList;
    }

    /**
     * 云潭街道是否能生成excel、pdf检查
     *
     * @param formSummaryList
     * @return
     */
    private List<Integer> checkParamYunTanStreet(List<Sqfw_formSummary> formSummaryList, String companyName) {
        List<Integer> excelNameList = Lists.newArrayList();
        FireHiddenExcelParamYuHongSQDTO excelParamYuHongSQDTO = new FireHiddenExcelParamYuHongSQDTO();
        excelParamYuHongSQDTO.setFormSummaryList(formSummaryList);
        excelParamYuHongSQDTO.setCompleteUnitName(companyName);
        //zhangp 2023-12-18 根据枚举类型获取文档数检测数据
        // excel数据检测
        List<YunTanExcelType> yunTanExcelTypes = List.of(YunTanExcelType.values());
        for (YunTanExcelType ye : yunTanExcelTypes) {
            excelParamYuHongSQDTO.setFileIndex(ye.getCode());
            String riskHiddenStatus = YuHongMenStreetFireHiddenExcelUtils.createExcelSQ(excelParamYuHongSQDTO, "isCheckData");
            if (StringUtils.isNotBlank(riskHiddenStatus) && riskHiddenStatus.equals("true")) {
                excelNameList.add(ye.getCode());
            }
        }
        // pdf数据检测，暂时不处理，目前云潭街道只有一个pdf，并且一定会生成该pdf
        List<YunTanPdfType> yunTanPdfTypes = List.of(YunTanPdfType.values());
        for (YunTanPdfType pdf : yunTanPdfTypes) {
        }

        return excelNameList;
    }

    /**
     * 大营路街道是否能生成excel检查
     *
     * @param formSummaryList
     * @return
     */
    private List<Integer> checkParamDaYingLuStreet(List<Sqfw_formSummary> formSummaryList, String companyName) {
        List<Integer> excelNameList = Lists.newArrayList();
        AtomicInteger count = new AtomicInteger(0);
        List<DaYingLuExcelType> daYingLuExcelTypes = List.of(DaYingLuExcelType.values());
        try {
            FireHiddenExcelParamDaYingLuSQDTO dto = new FireHiddenExcelParamDaYingLuSQDTO();
            dto.setFormSummaryList(formSummaryList);
            dto.setCompleteUnitName(companyName);
            for (DaYingLuExcelType de : daYingLuExcelTypes) {
                if (DaYingLuExcelType.PUBLIC_SECURITY_STANDING_BOOK.getCode() == de.getCode() || DaYingLuExcelType.PUBLIC_SECURITY_STANDING_PDF.getCode() == de.getCode()) {
                    continue;
                }
                dto.setFileIndex(de.getCode());
                FireHiddenExcelParamDaYingLuSQDTO fhDTO = new FireHiddenExcelParamDaYingLuSQDTO();
                BeanUtil.copyProperties(dto, fhDTO);
                executorService.execute(() -> {
                    String threeDetailedStatus = DaYingLuStreetFireHiddenExcelUtils.createFireHiddenExcelDaYingLuSQ(fhDTO, "isCheckData");
                    if (StringUtils.isNotBlank(threeDetailedStatus) && threeDetailedStatus.equals("true")) {
                        excelNameList.add(fhDTO.getFileIndex());
                    }
                    count.incrementAndGet();
                });
            }
        } catch (Exception e) {
            log.error("SqfwFormSummaryServiceImpl.checkParamDaYingLuStreet检测大营路excel异常:" + e.getMessage());
            throw new ServiceException("检测大营路excel数据异常");
        }
        while (count.get() < (daYingLuExcelTypes.size() - 2)) {
            continue;
        }
        return excelNameList;
    }

    /**
     * 入户调查模板下载
     *
     * @param sqfwId
     * @param excelType
     * @param fileNameSuffix
     * @return url
     * @author zhangp
     * @date 2023-11-23
     */
    private String generateHouseSurveyTemplateExcelForApp(String sqfwId, String excelType, String fileNameSuffix, String isWord, String isTemplate) {
        String unitName = null;
        String county = null;
        if (StringUtils.isNotBlank(sqfwId)) {
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
            unitName = serviceRecord.getCompanyName();
            county = serviceRecord.getCounty();
        } else {
            String userId = SecurityUtil.getUserId();
            Sys_user sysUser = sysUserService.fetch(userId);
            unitName = sysUser.getUnitName();
            county = sysUser.getCounty();
        }
        if (StringUtils.isNotBlank(isWord) && "word".equals(isWord)) {
            return houseSurveyWordTemplate(unitName);
        }
        return CommonComponent.generateHouseSurveyFormExcelForApp(null, Lists.newArrayList(), excelType, fileNameSuffix, unitName, county, isTemplate);
    }

    private String houseSurveyWordTemplate(String unitName) {
        Map<String, Object> paramMap = Maps.newHashMap();
        paramMap.put("unitName", unitName);
        paramMap.put("a16Type", null);
        String fillDateFormatStr = "yyyy 年 MM 月 dd 日";
        String fillDateStr = DateUtil.format(new Date(), fillDateFormatStr);
        paramMap.put("fillDateStr", fillDateStr);
        paramMap.put("a1", null);
        paramMap.put("a4", null);
        paramMap.put("a5", null);
        paramMap.put("a2", null);
        paramMap.put("a8", null);
        paramMap.put("a11s", null);
        paramMap.put("a12s", null);
        paramMap.put("a20", null);
        //String fileName = "进家入户宣传登记表集合";
        String fileName = DownLoadFileNameEnum.HOME_REGISTRATION_PDF.getName();
        GenerateWordAndPdfUrlVO wordVO = wordAndUpload(paramMap, "houseSurveyFormSNSQ.docx", fileName, fileName);
        if (StringUtils.isBlank(wordVO.getWordUrl())) {
            log.error("SqfwFormSummaryServiceImpl.generateHouseSurveyTemplateExcelForApp:入户调查下载模板失败！");
            throw new ServiceException("下载模板失败！");
        } else {
            return wordVO.getWordUrl();
        }
    }

    /**
     * 垃圾分类模板下载
     *
     * @param sqfwId
     * @param fileNameSuffix
     * @return url
     * @author zhangp
     * @date 2023-11-23
     */
    private String generateRubbishClassifyTemplateExcelForApp(String sqfwId, String fileNameSuffix, String isWord) {
        String unitName = null;
        String community = null;
        String county = null;
        if (StringUtils.isNotBlank(sqfwId)) {
            Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
            unitName = serviceRecord.getCompanyName();
            community = serviceRecord.getCommunity();
            county = serviceRecord.getCounty();
        } else {
            String userId = SecurityUtil.getUserId();
            Sys_user sysUser = sysUserService.fetch(userId);
            unitName = sysUser.getUnitName();
            community = sysUser.getCommunity();
            county = sysUser.getCounty();
        }
        if (StringUtils.isNotBlank(isWord) && "word".equals(isWord)) {
            GenerateWordAndPdfUrlVO wordVO = new GenerateWordAndPdfUrlVO();
            //String fileName = community + "垃圾分类巡查表-" + DateUtil.format(new Date(), "yyyyMMddHHmmss");
            String downloadFileName = DownLoadFileNameEnum.RUBBISH_CLASSIFICATION_PUBLICIZE.getName();
            String fileName = String.format("%s%s-%s", community, downloadFileName, DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            if (unitName.contains("云潭街道")) {
                // 如果为宇虹社区 则使用宇虹社区的
                wordVO = CommonFormOfficeUtils.wordAndUpload(null, "refuseClassifyYuHongSQ.docx", fileName, "垃圾分类");
            } else {
                wordVO = CommonFormOfficeUtils.wordAndUpload(null, "refuseClassify.docx", fileName, "垃圾分类");
            }
            if (StringUtils.isBlank(wordVO.getWordUrl())) {
                log.error("SqfwFormSummaryServiceImpl.generateRubbishClassifyTemplateExcelForApp:垃圾分类巡查下载模板失败！");
                throw new ServiceException("下载模板失败！");
            } else {
                return wordVO.getWordUrl();
            }
        }

        RefuseClassifyExcelParamDTO excelParamDTO = new RefuseClassifyExcelParamDTO();
        excelParamDTO.setFillDate(new Date());
        excelParamDTO.setSignalPersonImgUrl("");
        excelParamDTO.setAreaLevel(community + county);
        excelParamDTO.setCompleteUnitName(unitName);
        excelParamDTO.setFormSummaryList(Lists.newArrayList());
        try {
            excelParamDTO.setFileNameSuffix(fileNameSuffix);
            return RefuseClassifyOfficeUtils.createRefuseClassifyExcel(excelParamDTO, null);
        } catch (Exception e) {
            log.error("SqfwFormSummaryServiceImpl.generateRubbishClassifyTemplateExcelForApp>下载垃圾分类模板异常:{}", e.getMessage());
            throw new ServiceException("下载垃圾分类模板异常!");

        }
    }

    /**
     * 根据summaryId下载Excel（后台管理系统）
     * Add by LJT 2023-10-10
     */
    private String generateFireHiddenCollectionExcelForBM(List<String> sumIds, String workOrderId, String
            userId, Integer fileIndex, String fileNameSuffix) {
        if (sumIds.size() == 0) return "";
        Cnd cnd = Cnd.NEW();

        cnd.and("id", "in", sumIds);

        if (StringUtils.isNotBlank(workOrderId)) {
            cnd.and("work_order_id", "=", workOrderId);
        }

        cnd.orderBy("fill_date", "asc");

        List<Sqfw_formSummary> formSummaryList = query(cnd);

        String sqfwId = fetch(sumIds.get(0)).getSqfwId();
        Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);

        AbstractExcelParamDTO excelParamDTO = new AbstractExcelParamDTO();
        excelParamDTO.setFillDate(new Date());
        excelParamDTO.setSignalPersonImgUrl("");
        excelParamDTO.setUnitNamePrefix(serviceRecord.getCompanyName());
        excelParamDTO.setCompleteUnitName(serviceRecord.getCompanyName());

        excelParamDTO.setFormSummaryList(formSummaryList);

        Sys_user createServiceRecordUser = sysUserService.getUserById(serviceRecord.getUser_id());
        String unitId = createServiceRecordUser.getUnitId();
        Sys_unit unit = sysUnitService.getMasterCompany(unitId);

        String unitName = unit.getName();
        // 油榨街街道的
        if (unitName.contains("油榨街")) {
            excelParamDTO.setFileNameSuffix(fileNameSuffix);
            return FireHiddenOfficeUtils.createFireHiddenExcelYouZhaJieShiNanSQ(excelParamDTO, null);
        }

        // 金元社区的
        if (unitName.contains("金元") || unitName.contains("润兴")) {
            Sys_user createFileUser = sysUserService.fetch(userId);

            FireHiddenExcelParamJinYuanSQDTO dto = new FireHiddenExcelParamJinYuanSQDTO();
            BeanUtil.copyProperties(excelParamDTO, dto);

            if (unitName.contains("金元")) {
                dto.setVisAndInsExcelTitlePrefix(StrFormatter.format("金阳街道金元社区九小场所{}", DateUtil.format(dto.getFillDate(), "yyyy年MM月")));
                dto.setGasInsExcelTitlePrefix("金阳街道金元社区");
                dto.setGasRecExcelTitlePrefix("观山湖区金元社区");
                dto.setFireSafetyExcelTitlePrefix("金阳街道金元社区");
            }

            if (unitName.contains("润兴")) {
                dto.setVisAndInsExcelTitlePrefix(StrFormatter.format("金阳街道润兴居委会{}", DateUtil.format(dto.getFillDate(), "yyyy年MM月")));
                dto.setGasInsExcelTitlePrefix("金阳街道润兴居委会");
                dto.setGasRecExcelTitlePrefix("观山湖区润兴居委会");
                dto.setFireSafetyExcelTitlePrefix("金阳街道润兴居委会");
            }

            dto.setCreateUserName(createFileUser.getUsername());
            dto.setCreateUserPhone(createFileUser.getLoginname());
            dto.setCompleteUnitName(unitName);

            if (fileIndex == null) fileIndex = 1;
            dto.setFileIndex(fileIndex);

            // 如果是生成台账，则需要查询一些数据用来进行填装
            if (fileIndex == 0 || fileIndex == 4) {
                List<Sqfw_formSummary> jinYuanFormSummaryList = dto.getFormSummaryList();

                Map<String, Sqfw_formSummary> latestA1AndA13Map = Maps.newHashMap();
                for (Sqfw_formSummary jinYuanFormSummary : jinYuanFormSummaryList) {
                    String jinYuanA1 = jinYuanFormSummary.getA1();
                    String jinYuanA13 = jinYuanFormSummary.getA13();

                    if (jinYuanA13.equals("整改完成")) {
                        Cnd jinYuanCnd = Cnd.NEW();
                        jinYuanCnd.and("a1", "=", jinYuanA1).and("a13", "=", "有");
                        jinYuanCnd.orderBy("fill_date", "desc");
                        Sqfw_formSummary jinYuanQueryFormSummary = fetch(jinYuanCnd);
                        if (jinYuanQueryFormSummary != null)
                            latestA1AndA13Map.put(jinYuanQueryFormSummary.getA1(), jinYuanQueryFormSummary);
                    }

                }
                dto.setLatestA1AndA13Map(latestA1AndA13Map);
            }

            // 生成文件
            excelParamDTO.setFileNameSuffix(fileNameSuffix);
            VisAndInsForJinYangJieDaoExcelVO jinYuanFireHiddenExcelVO = FireHiddenOfficeUtils.createFireHiddenExcelJinYuanSQ(dto, null);
            if (jinYuanFireHiddenExcelVO.getErrorStatus()) return null;

            if (fileIndex == 1) return jinYuanFireHiddenExcelVO.getVisAndInsExcelUrl();
            if (fileIndex == 2) return jinYuanFireHiddenExcelVO.getGasInsExcelUrl();
            if (fileIndex == 3) return jinYuanFireHiddenExcelVO.getGasRecExcelUrl();
            if (fileIndex == 4) return jinYuanFireHiddenExcelVO.getStandingBookExcelUrl();

            if (fileIndex == 0)
                return StrFormatter.format("{},{},{},{}", jinYuanFireHiddenExcelVO.getVisAndInsExcelUrl(),
                        jinYuanFireHiddenExcelVO.getGasInsExcelUrl(), jinYuanFireHiddenExcelVO.getGasRecExcelUrl(), jinYuanFireHiddenExcelVO.getStandingBookExcelUrl());
        }

        //大营路街道
        if (unitName.contains("大营路街道")) {
            Sys_user createFileUser = sysUserService.fetch(userId);
            FireHiddenExcelParamDaYingLuSQDTO dto = new FireHiddenExcelParamDaYingLuSQDTO();
            BeanUtil.copyProperties(excelParamDTO, dto);
            dto.setCreateUserName(createFileUser.getUsername());
            dto.setCreateUserPhone(createFileUser.getLoginname());
            dto.setFileIndex(fileIndex);
            dto.setCompleteUnitName(unitName);
            dto.setArea(serviceRecord.getDistrict());
            dto.setStreet(serviceRecord.getCounty());
            return DaYingLuStreetFireHiddenExcelUtils.createFireHiddenExcelDaYingLuSQ(dto, null);
        }

        // 其他社区的
        return FireHiddenOfficeUtils.createFireHiddenExcel(excelParamDTO, null);
    }

    /**
     * 根据summaryId下载Excel集合（后台管理系统）
     * Add by LJT 2023-10-10
     */
    public String generateServiceRecordExcelCollForBM(List<String> sumIdList, String userId, Integer fileIndex) {
        if (sumIdList.size() == 0) {
            return null;
        }

        String fileNameSuffix = StrFormatter.format("集合{}", DateUtil.format(new Date(), "yyyyMMddHHmmss"));

        return generateFireHiddenCollectionExcelForBM(sumIdList, null, userId, fileIndex, fileNameSuffix);
    }

    @Override
    public void handleFormSummaryAndCenSusPaperForHouseSurveyDelete(Sqfw_formSummary formSummary) {
        if (!formSummary.getType().equals(SqfwFormSummaryConstants.house_survey_form)) return;
        if (StringUtils.isBlank(formSummary.getA7())) return;
        String a7 = formSummary.getA7();

        List<Sqfw_cenSusPaper> a7UserList = JSONObject.parseArray(a7, Sqfw_cenSusPaper.class);
        Set<String> preUpdateOrDeleteIdSet = a7UserList.stream().map(Sqfw_cenSusPaper::getId).collect(Collectors.toSet());

        // 使用a1 a4 a5 unitId查询上一次巡查的结果
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getA1, "=", formSummary.getA1()).and(Sqfw_formSummary::getA4, "=", formSummary.getA4())
                .and(Sqfw_formSummary::getA5, "=", formSummary.getA5()).and(Sqfw_formSummary::getUnitId, "=", formSummary.getUnitId())
                .and(Sqfw_formSummary::getId, "!=", formSummary.getId());
        cnd.desc("fill_date");

        Sqfw_formSummary lastFormSummary = fetch(cnd);
        if (lastFormSummary == null) {
            // sqfwCenSusPaperService.delete(Lists.newArrayList(preUpdateOrDeleteIdSet));
            List<Sqfw_cenSusPaper> cenSusPaperList = Lists.newArrayList();
            //zhangp 2024-01-08 当删除入户调查PDF时住户信息清空对应字段，网格、院落名称、楼栋、门牌、更新时间
            for (String id : preUpdateOrDeleteIdSet) {
                Sqfw_cenSusPaper sqfwCenSusPaper = sqfwCenSusPaperService.fetch(id);
                sqfwCenSusPaper.setGrid(null);
                sqfwCenSusPaper.setCourtyard(null);
                sqfwCenSusPaper.setBuilding(null);
                sqfwCenSusPaper.setHouseNumber(null);
                sqfwCenSusPaper.setUpdateDate(DateUtil.parseDate("0001-01-01 00:00:00"));
                sqfwCenSusPaperService.update(sqfwCenSusPaper);
                cenSusPaperList.add(sqfwCenSusPaper);
            }
            //1 记录更新日志
            sysLogService.insertUpdateLog(SecurityUtil.getUserId(), JSONObject.toJSONString(cenSusPaperList), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                    "com.budwk.app.sqfw.services.impl.SqfwFormSummaryServiceImpl.handleFormSummaryAndCenSusPaperForHouseSurveyDelete",
                    "com.budwk.app.sqfw.controllers.admin.SqfwFormSummaryServiceImpl.deleteAndUpdateWO");

            return;
        }

        String lastA7 = lastFormSummary.getA7();
        if (StringUtils.isBlank(lastA7)) return;
        List<Sqfw_cenSusPaper> lastA7UserList = JSONObject.parseArray(lastA7, Sqfw_cenSusPaper.class);

        Map<String, Sqfw_cenSusPaper> existCenMap = Maps.newHashMap();
        for (Sqfw_cenSusPaper lastCenPaper : lastA7UserList) {
            existCenMap.put(lastCenPaper.getId(), lastCenPaper);
        }
        List<Sqfw_cenSusPaper> cenSusPaperList = Lists.newArrayList();
        for (String id : preUpdateOrDeleteIdSet) {
            if (!existCenMap.containsKey(id)) {
                /*
                // 需要删除的数据
                sqfwCenSusPaperService.delete(id);
                */
                //zhangp 2024-01-08 当删除入户调查PDF时住户信息清空对应字段，网格、院落名称、楼栋、门牌、更新时间
                Sqfw_cenSusPaper sqfwCenSusPaper = sqfwCenSusPaperService.fetch(id);
                sqfwCenSusPaper.setGrid(null);
                sqfwCenSusPaper.setCourtyard(null);
                sqfwCenSusPaper.setBuilding(null);
                sqfwCenSusPaper.setHouseNumber(null);
                sqfwCenSusPaper.setUpdateDate(DateUtil.parseDate("0001-01-01 00:00:00"));
                sqfwCenSusPaperService.update(sqfwCenSusPaper);
                cenSusPaperList.add(sqfwCenSusPaper);
            } else {
                // wzy 2023-11-16 需要将本次更新的人的数据从上一次入户调查中恢复
                Sqfw_cenSusPaper lastCenSusPaper = existCenMap.get(id);
                if (sqfwCenSusPaperService.fetch(lastCenSusPaper.getId()) != null) {
                    sqfwCenSusPaperService.update(lastCenSusPaper);
                }
            }
        }

        //1 记录更新日志
        sysLogService.insertUpdateLog(SecurityUtil.getUserId(), JSONObject.toJSONString(cenSusPaperList), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.impl.SqfwFormSummaryServiceImpl.handleFormSummaryAndCenSusPaperForHouseSurveyDelete",
                "com.budwk.app.sqfw.controllers.admin.SqfwFormSummaryServiceImpl.deleteAndUpdateWO");

    }

    @Override
    public void batchDeleteFormSummary(List<String> formSummaryIds) {
        if (formSummaryIds == null || formSummaryIds.size() == 0) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        // 查询数据
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_formSummary::getId, "in", formSummaryIds);
        List<Sqfw_formSummary> list = this.query(cnd);
        log.info("batchDeleteFormSummary Sqfw_formSummary query res:{}", JSONObject.toJSONString(list));
        if (list.isEmpty()) {
            throw new AppException(ResultCode.NULL_DATA_ERROR.getMsg());
        }
        String userId = SecurityUtil.getUserId();
        // 异步执行删除操作
        CompletableFuture[] cf = list.stream().map(data -> CompletableFuture.runAsync(() ->
                        batchDeleteData(userId, data), taskUpdateExecutor)
                .thenApply(r -> r)).toArray(CompletableFuture[]::new);
        CompletableFuture.allOf(cf).join();
    }

    private void batchDeleteData(String userId, Sqfw_formSummary data) {
        //1 记录日志
        sysLogService.insertDelLog(userId, JSONObject.toJSONString(data), Sqfw_cenSusPaper.class.getAnnotation(Table.class).value(),
                "com.budwk.app.sqfw.services.impl.SqfwFormSummaryServiceImpl.batchDeleteFormSummary",
                "com.budwk.app.sqfw.controllers.admin.SqfwFormSummaryController.batchDeleteFormSummary");
        // 2 删除数据
        sqfwCompleteflowService.deleteAndUpdateWO(data.getSqfwFlowId());
    }


    /**
     * 社会治安 生成pdf
     *
     * @param userId              用户ID
     * @param formSummaryWithFlow G工作流
     */
    @Override
    public void generatePublicSecurityPdf(String userId, SqfwFormSummaryWithFlowDTO formSummaryWithFlow) {
        insertWordFlowAndFormSummary(userId, formSummaryWithFlow, SqfwFormSummaryConstants.public_security);

        Sqfw_completeflow completeFlow = formSummaryWithFlow.getCompleteFlow();
        Sqfw_formSummary formSummary = formSummaryWithFlow.getFormSummary();

        executorService.execute(() -> {
            doGeneratePublicSecurityPdf(completeFlow, formSummary, true);
        });
    }

    private void doGeneratePublicSecurityPdf(Sqfw_completeflow completeFlow, Sqfw_formSummary formSummary, boolean sendMsgFlag) {
        boolean successFlag = false;
        String resourcePath = "";
        String sendMsgPhone = "";
        Sqfw_Sms_Msg smsMsg = null;

        try {
            String unitId = formSummary.getUnitId();
            Sys_unit unit = sysUnitService.fetch(unitId);

            FireHiddenCheckWordDTO wordDTO = new FireHiddenCheckWordDTO();
            BeanUtil.copyProperties(formSummary, wordDTO);
            wordDTO.setCompleteUnitName(unit.getName());
            wordDTO.setUnitName(unit.getName());

            GenerateWordAndPdfUrlVO wordVO = creatPublicSecurityFormWordAndPDFByUnitName(wordDTO);
            if (StringUtils.isNotBlank(wordVO.getPdfUrl())) {
                resourcePath = wordVO.getPdfUrl();
                sendMsgPhone = wordVO.getPhone();
                sendMsgPhone = StringUtils.isBlank(sendMsgPhone) ? formSummary.getA8() : sendMsgPhone;
                successFlag = true;
                smsMsg = wordVO.getSmsMsg();
            }
        } catch (Exception e) {
            throw new ServiceException("更新社区治安异常");

        }

        // 生成完成之后更新工作流状态
        if (successFlag) completeFlow.setResourcePath(resourcePath);
        else completeFlow.setResourcePath("error");
        sqfwCompleteflowService.update(completeFlow);

        // 当生成完毕之后就直接发送webSocket消息或者短信消息
        sendMsgAfterFireHiddenPdfOrExcel(completeFlow.getUserId(), sendMsgPhone, sendMsgFlag, smsMsg);
    }

    private GenerateWordAndPdfUrlVO creatPublicSecurityFormWordAndPDFByUnitName(FireHiddenCheckWordDTO wordDTO) {

        Sys_user sysUser = sysUserService.getUserById(wordDTO.getCreateBy());
        wordDTO.setCreateUserName(sysUser.getUsername());

        wordDTO.setProvince(sysUser.getProvince());
        wordDTO.setCity(sysUser.getCity());
        wordDTO.setDistrict(sysUser.getDistrict());
        wordDTO.setCounty(sysUser.getCounty());
        wordDTO.setCommunity(sysUser.getCommunity());
        DaYingLuStreetFireHiddenCheckWordDTO daYingLuWordDTO = new DaYingLuStreetFireHiddenCheckWordDTO();
        BeanUtil.copyProperties(wordDTO, daYingLuWordDTO);

        String a18 = wordDTO.getA18();
        Map<String, List<String>> userSignatureMap = getUserSignatureMap(a18, wordDTO.getUnitId());

        // 含有签名图片的和没有签名图片的
        daYingLuWordDTO.setA18NoSignatureUsers(userSignatureMap.get("noSig"));
        daYingLuWordDTO.setA18UserSignatureUrls(userSignatureMap.get("sig"));

        return DaYingLuStreetPublicSecurityOfficeUtils.createPublicSecurityPDF(daYingLuWordDTO);

    }

    /**
     * 大营路社会治安excel下载
     *
     * @param sqfwId      服务ID
     * @param workOrderId 工作流程
     * @param userId      当前登录人
     * @param fileIndex   文件索引
     * @return
     */
    @Override
    public String generatePublicSecurityExcelForApp(String sqfwId, String workOrderId, String userId, Integer fileIndex) {

        Cnd cnd = Cnd.NEW();
        cnd.and("sqfwId", "=", sqfwId).and("type", "=", SqfwFormSummaryConstants.public_security);
        if (StringUtils.isNotBlank(workOrderId)) {
            cnd.and("work_order_id", "=", workOrderId);
        }
        cnd.orderBy("fill_date", "asc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        Sqfw_servicerecord sqfwServicerecord = sqfwServicerecordService.fetch(sqfwId);
        if (formSummaryList.isEmpty()) return null;
        try {
            FireHiddenExcelParamDaYingLuSQDTO fireHiddenExcelParamDaYingLuSQDTO = new FireHiddenExcelParamDaYingLuSQDTO();
            fireHiddenExcelParamDaYingLuSQDTO.setFileIndex(fileIndex);
            fireHiddenExcelParamDaYingLuSQDTO.setFormSummaryList(formSummaryList);
            fireHiddenExcelParamDaYingLuSQDTO.setStreet(sqfwServicerecord.getCounty());
            String url = DaYingLuStreetPublicSecurityExcelUtils.createPublicSecurityDaYingLuSQ(fireHiddenExcelParamDaYingLuSQDTO);
            CommonComponent.insertDownRecordLog(sqfwId, JSONObject.toJSONString(Result.data(url)), "下载" + DaYingLuExcelType.PUBLIC_SECURITY_STANDING_BOOK.getName(), url, sqfwId);
            return url;
        } catch (Exception e) {
            log.error("SqfwFormSummaryServiceImpl.generatePublicSecurityExcelForApp社会治安重点风险场所台账异常:{}", e.getMessage());
            throw new ServiceException("社会治安重点风险场所台账异常");
        }

    }

    @Override
    public void retryGeneratePublicSecurityPdf(String userId, String sqfwFlowId) {
        // 首先根据工作流id查询到表单的数据
        Sqfw_completeflow sqfwCompleteFlow = sqfwCompleteflowService.fetch(sqfwFlowId);
        if (sqfwCompleteFlow == null) return;
        // 将工作流的pdf生成状态设置为creating
        sqfwCompleteFlow.setResourcePath("creating");
        sqfwCompleteflowService.update(sqfwCompleteFlow);

        // 然后组成相应的DTO 创建pdf
        Cnd cnd = Cnd.NEW().and("sqfw_flow_id", "=", sqfwFlowId);
        Sqfw_formSummary formSummaryOfFlow = fetch(cnd);

        executorService.execute(() -> {
            doGeneratePublicSecurityPdf(sqfwCompleteFlow, formSummaryOfFlow, false);
        });
    }

    @Override
    public List<Sqfw_formSummary> queryPlaceNameHistory(String placeName) {
        Cnd cnd = Cnd.NEW();
        cnd.and("type", "=", SqfwFormSummaryConstants.public_security);
        cnd.and("unit_id", "=", SecurityUtil.getUnitId());
        cnd.and("a1", "like", "%" + placeName + "%");
        cnd.orderBy("fill_date", "desc");
        List<Sqfw_formSummary> formSummaryList = query(cnd);
        List<Sqfw_formSummary> formSummaries = Lists.newArrayList();
        List<String> a1List = Lists.newArrayList();
        for (Sqfw_formSummary formSummary : formSummaryList) {
            if (a1List.contains(formSummary.getA1())) {
                continue;
            }
            Sqfw_formSummary sqfwFormSummary = new Sqfw_formSummary();
            sqfwFormSummary.setA1(formSummary.getA1());
            sqfwFormSummary.setA3(formSummary.getA3());
            sqfwFormSummary.setA2(formSummary.getA2());
            sqfwFormSummary.setA8(formSummary.getA8());
            sqfwFormSummary.setA16(formSummary.getA16());
            sqfwFormSummary.setA5(formSummary.getA5());
            formSummaries.add(sqfwFormSummary);
            a1List.add(formSummary.getA1());
        }
        return formSummaries;
    }


    private String generatePublicSecurityTemplateForApp(String sqfwId, Integer fileNameSuffix, String isWord) {
        try {
            String county = null;
            if (StringUtils.isNotBlank(sqfwId)) {
                Sqfw_servicerecord serviceRecord = sqfwServicerecordService.fetch(sqfwId);
                county = serviceRecord.getCounty();
            } else {
               /* String userId = SecurityUtil.getUserId();
                Sys_user sysUser = sysUserService.fetch(userId);
                county = sysUser.getCounty();*/
                county = "";
            }
            if (null == fileNameSuffix) fileNameSuffix = DaYingLuExcelType.PUBLIC_SECURITY_STANDING_BOOK.getCode();
            FireHiddenExcelParamDaYingLuSQDTO fireHiddenExcelParamDaYingLuSQDTO = new FireHiddenExcelParamDaYingLuSQDTO();
            fireHiddenExcelParamDaYingLuSQDTO.setFileIndex(fileNameSuffix);
            fireHiddenExcelParamDaYingLuSQDTO.setStreet(county);
            fireHiddenExcelParamDaYingLuSQDTO.setFormSummaryList(Lists.newArrayList());
            return DaYingLuStreetPublicSecurityExcelUtils.createPublicSecurityDaYingLuSQ(fireHiddenExcelParamDaYingLuSQDTO);

        } catch (Exception e) {
            log.error("SqfwFormSummaryServiceImpl.generatePublicSecurityExcelForApp社会治安重点风险场所台账异常:{}", e.getMessage());
            throw new ServiceException("社会治安重点风险场所台账异常");
        }
    }

    /**
     * 判断多层嵌套数组内容是否为空
     *
     * @return false:空， true:非空
     */
    private Boolean checkArrayListEmpty(String arrayStr) {
        boolean res = false;
        if (StringUtils.isEmpty(arrayStr)) {
            return res;
        }
        try {
            List<String> arrayList = JSONObject.parseArray(arrayStr, String.class);
            if (arrayList.size() <= 0) {
                return res;
            }
            for (String arraySub : arrayList) {
                if (!arraySub.contains("[]")) {
                    res = true;
                    break;
                }
            }
        } catch (Exception ex) {
            log.info("SqfwFormSummaryServiceImpl checkArrayListEmpty 数组解析异常：{}", ex.getMessage());
            return res;
        }
        return res;
    }


    @Override
    public Result<?> downloadFileMerging(ServerFileMergingDTO serverFileMergingDTO) {
        Cnd cnd = Cnd.NEW();
        cnd.and("sqfw_id", "in", serverFileMergingDTO.getSqfwIds())
                .orderBy("create_date", "desc");
        //根据任务ID获取记录
        List<Sqfw_formSummary_new> sqfwFormSummaryNewList = sqfwFormsummaryNewService.query(cnd);
        if (ObjectUtils.isEmpty(sqfwFormSummaryNewList))
            throw new ServiceException(String.format("暂无数据无法合并%s!", serverFileMergingDTO.getFileType().toUpperCase()));
        List<String> type = sqfwFormSummaryNewList.stream().map(Sqfw_formSummary_new::getType).distinct().collect(Collectors.toList());
        if (type.size() > 1) {
            throw new ServiceException(String.format("任务类型不同无法合并%s!", serverFileMergingDTO.getFileType().toUpperCase()));
        }
        List<String> idList = sqfwFormSummaryNewList.stream().map(Sqfw_formSummary_new::getId).collect(Collectors.toList());
        //构造需要的参数
        List<ExcelCreateConfig> excelCreateConfigs = new ArrayList<>();
        ExcelCreateConfig excelCreateConfig = new ExcelCreateConfig();
        excelCreateConfig.setFileIdentity(serverFileMergingDTO.getFileCode());
        excelCreateConfigs.add(excelCreateConfig);
        SqfwCustomForAdminCommonVO bean = new SqfwCustomForAdminCommonVO();
        bean.setType(serverFileMergingDTO.getType());
        bean.setFormSummaryNewIdList(idList);
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        bean.setProvince(user.getProvince());
        bean.setCity(user.getCity());
        bean.setDistrict(user.getDistrict());
        bean.setCounty(user.getCounty());
        bean.setCommunity(user.getCommunity());

        //会议/活动/来访记录
        if (SupportBusinessTypeEnum.MEETING_ACTIVITY_VISIT_RECORD.getName().equals(bean.getType())) {
            MeetingService meetingService = NutzIocUtils.getBean(MeetingService.class);
            List<Integer> indexList = meetingService.generateMeetingCheckDataForAdmin(null, "select", String.join(",", idList));
            if (!indexList.contains(Integer.valueOf(serverFileMergingDTO.getFileCode()))) {
                throw new ServiceException(String.format("暂无数据无法合并%s!", serverFileMergingDTO.getFileType().toUpperCase()));
            }

            if (serverFileMergingDTO.getFileType().equalsIgnoreCase("PDF")) {
                GenerateWordAndPdfUrlVO generateWordAndPdfUrlVO = new GenerateWordAndPdfUrlVO();
                generateWordAndPdfUrlVO.setPdfUrl(meetingService.generateMeetingExcelCollZipForBM(null, Integer.valueOf(serverFileMergingDTO.getFileCode()), false, "select", String.join(",", idList)));
                return Result.data(generateWordAndPdfUrlVO);
            }
            if (serverFileMergingDTO.getFileType().equalsIgnoreCase("EXCEL")) {
                List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();
                GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
                generateExcelUrlVO.setExcelUrl(meetingService.generateMeetingExcelCollZipForBM(null, Integer.valueOf(serverFileMergingDTO.getFileCode()), false, "select", String.join(",", idList)));
                generateExcelUrlVOS.add(generateExcelUrlVO);
                return Result.data(generateExcelUrlVOS);
            } else {
                throw new ServiceException("下载文件类型不存在,只能是PDF或EXCEL");
            }

        } else {
            //通过五级加任务类型找到对应icoBean名称
            FileMergingBeanNameEnum fileMergingBeanNameEnum = FileMergingBeanNameEnum.getServiceByType(bean.getType(), user);
            if (ObjectUtils.isEmpty(fileMergingBeanNameEnum))
                throw new ServiceException("未配置对应街道服务,无法合并文档,请联系相关开发人员！");
            //根据拿到的beanName注入
            SqfwCustomForAdminCommonService sqfwCompleteflowService = NutzIocUtils.getPointBean(fileMergingBeanNameEnum.getBeanName(), SqfwCustomForAdminCommonService.class);
            checkFileData(sqfwCompleteflowService, serverFileMergingDTO, bean, excelCreateConfig);

            Set<String> specialType = Sets.newHashSet(SupportBusinessTypeEnum.RED_WHITE_RECORD.getName(), SupportBusinessTypeEnum.OLD_PEOPLE_SEEK.getName());
            if (serverFileMergingDTO.getFileType().equalsIgnoreCase("PDF")) {
                //PDF处理
                if (specialType.contains(serverFileMergingDTO.getType())) {
                    return Result.data(sqfwCompleteflowService.downloadPdfList(excelCreateConfigs, bean));
                } else {
                    return Result.data(sqfwCompleteflowService.downloadPdf(excelCreateConfigs, bean));
                }
            } else if (serverFileMergingDTO.getFileType().equalsIgnoreCase("EXCEL")) {
                //excel处理
                return Result.data(sqfwCompleteflowService.downloadExcel(excelCreateConfigs, bean));
            } else {
                throw new ServiceException("下载文件类型不存在,只能是PDF或EXCEL");
            }
        }

    }

    private void checkFileData(SqfwCustomForAdminCommonService sqfwCompleteflowService, ServerFileMergingDTO serverFileMergingDTO, SqfwCustomForAdminCommonVO bean, ExcelCreateConfig excelCreateConfig) {
        Set<String> noCheckData = Sets.newHashSet(SupportBusinessTypeEnum.OLD_CARE_SERVICE.getName());
        if (SupportBusinessTypeEnum.RED_WHITE_RECORD.getName().equals(serverFileMergingDTO.getType()) && "PDF".equalsIgnoreCase(serverFileMergingDTO.getFileType())) {
            noCheckData.add(SupportBusinessTypeEnum.RED_WHITE_RECORD.getName());
        }
        if (noCheckData.contains(serverFileMergingDTO.getType())) {
            return;
        }
        List<CheckDataForAdminVO> checkDataForAdminVOS = sqfwCompleteflowService.checkDataInfoList(bean);
        if (ObjectUtils.isEmpty(checkDataForAdminVOS) || checkDataForAdminVOS.isEmpty()) {
            throw new ServiceException(String.format("暂无数据无法合并%s!", serverFileMergingDTO.getFileType().toUpperCase()));
        }
        Map<String, List<CheckDataForAdminVO>> collect = checkDataForAdminVOS.stream().collect(Collectors.groupingBy(CheckDataForAdminVO::getFileIdentity));
        List<CheckDataForAdminVO> checkDataForAdminVOSByCode = collect.get(excelCreateConfig.getFileIdentity());
        if (ObjectUtils.isEmpty(checkDataForAdminVOSByCode) || checkDataForAdminVOSByCode.isEmpty()) {
            throw new ServiceException(String.format("暂无数据无法合并%s!", serverFileMergingDTO.getFileType().toUpperCase()));
        }
        boolean flag = checkDataForAdminVOSByCode.get(0).getCreateConditionFlag();
        if (!flag) {
            throw new ServiceException(String.format("暂无数据无法合并%s!", serverFileMergingDTO.getFileType().toUpperCase()));
        }
    }


    //我的页面-文档合并时排除creating中的
    private String generateServiceRecordPdfCollNew(List<ServiceRecordPdfOrExcelCollDTO> conditionList, Integer fileIndex) {

        List<PdfResourceSortBO> pdfBoList = Lists.newArrayList();

        /*Set<String> flowTypeSet = Sets.newHashSet("垃圾分类", ServiceTypeEnum.SECURITY_INVESTIGATION.getName(), "入户调查",
                ServiceTypeEnum.MEETING_RECORD.getName(), "社会治安", "社会治安重点场所巡查",
                ServiceTypeEnum.SAFE_CHECK.getName(),
                ServiceTypeEnum.OLD_CARE_SERVICE.getName(), SqfwFormSummaryConstants.red_white_record);*/
        Set<String> flowTypeSet = Sets.newHashSet(SupportBusinessTypeEnum.MEET_RECORD.getCode(), SupportBusinessTypeEnum.SAFE_CHECK.getName());
        for (SupportBusinessTypeEnum supportBusinessTypeEnum : SupportBusinessTypeEnum.values()) {
            flowTypeSet.add(supportBusinessTypeEnum.getName());
        }
        Set<String> fileReportTypeSet = Sets.newHashSet("12345", "简报", "八单一表", "日报", "其他");
        // 字典系统重构新需求功能(重构功能开发的)
        Map<String, ServiceRecordPdfOrExcelCollDTO> fromFlowDTOMap = Maps.newHashMap();
        Map<String, ServiceRecordPdfOrExcelCollDTO> fromFileReportMap = Maps.newHashMap();
        for (ServiceRecordPdfOrExcelCollDTO serviceRecordPdfOrExcelCollDTO : conditionList) {
            String serviceType = serviceRecordPdfOrExcelCollDTO.getServiceType();
            if (flowTypeSet.contains(serviceType))
                fromFlowDTOMap.put(serviceRecordPdfOrExcelCollDTO.getSqfwId(), serviceRecordPdfOrExcelCollDTO);
            if (fileReportTypeSet.contains(serviceType))
                fromFileReportMap.put(serviceRecordPdfOrExcelCollDTO.getSqfwId(), serviceRecordPdfOrExcelCollDTO);
        }

        // 首先查询存储于sqfw_complete_flow中的数据
        if (fromFlowDTOMap.size() > 0) {

            Map<String, Date> completeFlowIdDateMap = new HashMap<>();
            List<String> flowIdList = new ArrayList<>();

            // 查询新表数据
            Cnd aNew = Cnd.NEW();
            SqlExpressionGroup where = aNew.where();
            where.andIn(Sqfw_formSummary_new::getSqfwId, fromFlowDTOMap.keySet().toArray(new String[0]));
            aNew.orderBy(Sqfw_formSummary_new::getFillDate, "asc");
            List<Sqfw_formSummary_new> formSummaryNews = sqfwFormsummaryNewService.query(aNew);
            completeFlowIdDateMap = formSummaryNews.stream()
                    .collect(Collectors.toMap(Sqfw_formSummary_new::getSqfwFlowId, Sqfw_formSummary_new::getFillDate));
            flowIdList = formSummaryNews.stream().map(Sqfw_formSummary_new::getSqfwFlowId).collect(Collectors.toList());

            Cnd flowCnd = Cnd.NEW();
            flowCnd.and("id", "in", flowIdList);
            List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.query(flowCnd);
            for (Sqfw_completeflow completeFlow : completeFlowList) {
                //zhangp 20240318
                if (StringUtils.isBlank(completeFlow.getResourcePath())
                        || completeFlow.getResourcePath().equals("creating")
                        || completeFlow.getResourcePath().equals("error")) {
                    continue;
                }
                PdfResourceSortBO bo = new PdfResourceSortBO();
                Date fillDate = completeFlowIdDateMap.get(completeFlow.getId());
                bo.setSortDate(fillDate);
                bo.setSqfwId(completeFlow.getSqfwId());
                bo.setPdfPath(completeFlow.getResourcePath());
                bo.setServiceType(completeFlow.getFileType());
                pdfBoList.add(bo);
            }
        }

        // 然后从file_report中根据服务id查询出相关的数据 这一步我们使用循环查询的方式来操作
        if (fromFileReportMap.size() > 0) {
            Set<String> sqfwIdSet = fromFileReportMap.keySet();
            for (String sqfwId : sqfwIdSet) {

                Set<String> existedReportNameSet = Sets.newHashSet();

                Cnd fileReportCnd = Cnd.NEW();
                fileReportCnd.and("sqfw_id", "=", sqfwId).orderBy("create_date", "desc");
                List<Sqfw_reportFile> reportFileList = reportFileService.query(fileReportCnd);
                for (Sqfw_reportFile reportFile : reportFileList) {
                    String reportName = reportFile.getReportName();
                    if (StringUtils.isNotBlank(reportName) && !existedReportNameSet.contains(reportName)) {
                        existedReportNameSet.add(reportName);

                        PdfResourceSortBO bo = new PdfResourceSortBO();
                        bo.setSortDate(reportFile.getCreateDate());
                        bo.setSqfwId(reportFile.getSqfwId());
                        bo.setPdfPath(reportFile.getPdfFileUrl());
                        bo.setServiceType(reportFile.getServiceRecordType());
                        pdfBoList.add(bo);
                    }
                }
            }
        }

        // 将这些文档按照时间先后顺序进行排序
        pdfBoList.sort(Comparator.comparing(PdfResourceSortBO::getSortDate));

        List<String> pdfPathList = pdfBoList.stream().map(PdfResourceSortBO::getPdfPath).collect(Collectors.toList());

        // 用于生成文件规则
        Set<String> serviceTypeTotalSet = conditionList.stream().map(ServiceRecordPdfOrExcelCollDTO::getServiceType).collect(Collectors.toSet());
        String fileNameTemplate = "{}文档集合{}";

        String fileNamePrefix = "工作文档";
        if (serviceTypeTotalSet.size() == 1) fileNamePrefix = serviceTypeTotalSet.iterator().next();
        String fileName = StrFormatter.format(fileNameTemplate, fileNamePrefix, DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        return CommonFormOfficeUtils.createConvergePdfAndUpload(pdfPathList, fileName);
    }

}
